first
This commit is contained in:
43
server-api/app/support/ContentImageService.php
Normal file
43
server-api/app/support/ContentImageService.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace app\support;
|
||||
|
||||
use support\Request;
|
||||
use function md5;
|
||||
use function sprintf;
|
||||
use function strtolower;
|
||||
|
||||
class ContentImageService
|
||||
{
|
||||
public function upload(Request $request, string $inputName = 'file'): array
|
||||
{
|
||||
$file = $request->file($inputName);
|
||||
if (!$file || !$file->isValid()) {
|
||||
throw new \RuntimeException('上传文件无效');
|
||||
}
|
||||
|
||||
$extension = strtolower($file->getUploadExtension() ?: 'jpg');
|
||||
if (!in_array($extension, ['jpg', 'jpeg', 'png', 'webp'], true)) {
|
||||
throw new \RuntimeException('仅支持上传 jpg、jpeg、png、webp 图片');
|
||||
}
|
||||
|
||||
$filename = sprintf('content_image_%s.%s', uniqid(), $extension);
|
||||
$relativeDir = 'uploads/content-images/' . date('Ymd');
|
||||
$relativePath = $relativeDir . '/' . $filename;
|
||||
$this->storage()->putUploadedFile($file, $relativePath);
|
||||
|
||||
$fileUrl = $this->storage()->publicUrl($request, $relativePath);
|
||||
|
||||
return [
|
||||
'file_id' => md5($relativePath),
|
||||
'file_url' => $fileUrl,
|
||||
'thumbnail_url' => $fileUrl,
|
||||
'name' => $file->getUploadName(),
|
||||
];
|
||||
}
|
||||
|
||||
private function storage(): FileStorageService
|
||||
{
|
||||
return new FileStorageService();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user