first
This commit is contained in:
64
server-api/app/support/CatalogTemplateSampleImageService.php
Normal file
64
server-api/app/support/CatalogTemplateSampleImageService.php
Normal file
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace app\support;
|
||||
|
||||
use support\Request;
|
||||
use function md5;
|
||||
use function sprintf;
|
||||
use function str_starts_with;
|
||||
use function strtolower;
|
||||
|
||||
class CatalogTemplateSampleImageService
|
||||
{
|
||||
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('upload_template_sample_%s.%s', uniqid(), $extension);
|
||||
$relativeDir = 'uploads/upload-template-samples/' . 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(),
|
||||
];
|
||||
}
|
||||
|
||||
public function delete(string $fileUrl): void
|
||||
{
|
||||
$relativePath = $this->storage()->storagePath($fileUrl);
|
||||
if (!str_starts_with($relativePath, 'uploads/upload-template-samples/')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->storage()->delete($relativePath);
|
||||
}
|
||||
|
||||
public function normalizeUrl(string $fileUrl, Request $request): string
|
||||
{
|
||||
return $this->storage()->normalizeUrl($fileUrl, $request);
|
||||
}
|
||||
|
||||
public function storagePath(string $fileUrl): string
|
||||
{
|
||||
return $this->storage()->storagePath($fileUrl);
|
||||
}
|
||||
|
||||
private function storage(): FileStorageService
|
||||
{
|
||||
return new FileStorageService();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user