UploadService.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Module\File\Services;
  3. use App\Module\File\Config\StorageConfig;
  4. use App\Module\File\Logics\DirLogic;
  5. use App\Module\File\Models\FileImg;
  6. use Illuminate\Http\UploadedFile;
  7. use Illuminate\Support\Facades\Storage;
  8. use Intervention\Image\ImageManager;
  9. use Intervention\Image\Drivers\Imagick\Driver;
  10. use Intervention\Image\Drivers\Gd\Driver as GdDriver;
  11. /**
  12. * 上传服务类
  13. *
  14. * 提供文件上传相关的服务
  15. */
  16. class UploadService
  17. {
  18. /**
  19. * 用户ID
  20. *
  21. * @var int
  22. */
  23. protected $userId;
  24. /**
  25. * 构造函数
  26. *
  27. * @param int $userId 用户ID
  28. */
  29. public function __construct(int $userId)
  30. {
  31. $this->userId = $userId;
  32. }
  33. /**
  34. * 上传图片
  35. *
  36. * @param UploadedFile $file 上传的文件
  37. * @param bool $private 是否私有
  38. * @return FileImg 图片模型
  39. * @throws \Exception 上传失败时抛出异常
  40. */
  41. public function uploadImg(UploadedFile $file, $private = false)
  42. {
  43. $dirLogic = new DirLogic();
  44. $dir = $dirLogic->getDir($this->userId);
  45. // 重绘
  46. $upfilepath = $file->getRealPath();
  47. // create image manager with desired driver
  48. $manager = new ImageManager(new Driver());
  49. // read image from file system
  50. $image = $manager->read($upfilepath);
  51. // resize image proportionally
  52. $image->scale($image->width(), $image->height());
  53. $path = $dir . '/' . uniqid() . '.webp';
  54. // save modified image in new format
  55. $webpimg = $image->toWebp();
  56. $fileString = $webpimg->toString();
  57. $size = $webpimg->size();
  58. // 保存
  59. $disk = StorageConfig::getStorage();
  60. $res = Storage::disk($disk)->put($path, $fileString);
  61. if ($res === false) {
  62. throw new \Exception('服务器错误,请联系客服.');
  63. }
  64. $f = new FileImg();
  65. $f->storage_disk = $disk;
  66. $f->path = $path;
  67. $f->user_id = $this->userId;
  68. $f->o_name = $file->getClientOriginalName();
  69. $f->type1 = 'webp';
  70. $f->fsize = $size;
  71. $f->private = (int)$private;
  72. $f->re_id = 0;
  73. $f->re_type = '';
  74. $f->save();
  75. $f->refresh();
  76. return $f;
  77. }
  78. }