TextbookCoverStorageService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Http\UploadedFile;
  4. use Illuminate\Support\Facades\Http;
  5. use Illuminate\Support\Facades\Log;
  6. use Illuminate\Support\Facades\Storage;
  7. use Illuminate\Support\Str;
  8. class TextbookCoverStorageService
  9. {
  10. /**
  11. * 保存教材封面上传到云存储,返回URL
  12. */
  13. public function uploadCover(UploadedFile $file, ?string $textbookId = null): ?string
  14. {
  15. // 验证文件类型
  16. $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp'];
  17. if (!in_array($file->getMimeType(), $allowedMimeTypes)) {
  18. Log::error('TextbookCoverStorageService: 不支持的文件类型', ['mime_type' => $file->getMimeType()]);
  19. return null;
  20. }
  21. // 验证文件大小(最大 5MB)
  22. $maxSize = 5 * 1024 * 1024;
  23. if ($file->getSize() > $maxSize) {
  24. Log::error('TextbookCoverStorageService: 文件过大', ['size' => $file->getSize()]);
  25. return null;
  26. }
  27. // 生成唯一文件名
  28. $extension = $file->getClientOriginalExtension();
  29. $filename = Str::uuid() . '.' . $extension;
  30. // 构建存储路径
  31. $directory = $textbookId ? "textbook-covers/{$textbookId}" : 'textbook-covers/temp';
  32. $path = $directory . '/' . $filename;
  33. // 获取文件二进制内容
  34. $binary = file_get_contents($file->getPathname());
  35. // 使用云存储服务
  36. $storageService = app(PdfStorageService::class);
  37. $url = $storageService->put($path, $binary);
  38. if (!$url) {
  39. Log::error('TextbookCoverStorageService: 上传失败', ['path' => $path]);
  40. return null;
  41. }
  42. Log::info('TextbookCoverStorageService: 上传成功', [
  43. 'path' => $path,
  44. 'url' => $url,
  45. 'textbook_id' => $textbookId,
  46. ]);
  47. return $url;
  48. }
  49. /**
  50. * 删除封面文件
  51. */
  52. public function deleteCover(string $url): bool
  53. {
  54. // 注意:又拍云和春笋云目前没有删除API
  55. // 这里只是记录日志,实际删除需要手动或定时任务处理
  56. Log::warning('TextbookCoverStorageService: 删除操作未实现', ['url' => $url]);
  57. return true;
  58. }
  59. /**
  60. * 获取存储驱动信息
  61. */
  62. public function getStorageInfo(): array
  63. {
  64. $driver = config('services.pdf_storage.driver', env('PDF_STORAGE_DRIVER', 'local'));
  65. return [
  66. 'driver' => $driver,
  67. 'name' => match ($driver) {
  68. 'upyun' => '又拍云',
  69. 'chunsun' => '春笋云',
  70. 'local' => '本地存储',
  71. default => '未知',
  72. },
  73. 'supports_delete' => false, // 又拍云和春笋都不支持删除API
  74. ];
  75. }
  76. }