| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace App\Module\File\Services;
- use App\Module\File\Config\StorageConfig;
- use App\Module\File\Logics\DirLogic;
- use App\Module\File\Models\FileImg;
- use Illuminate\Http\UploadedFile;
- use Illuminate\Support\Facades\Storage;
- use Intervention\Image\ImageManager;
- use Intervention\Image\Drivers\Imagick\Driver;
- use Intervention\Image\Drivers\Gd\Driver as GdDriver;
- /**
- * 上传服务类
- *
- * 提供文件上传相关的服务
- */
- class UploadService
- {
- /**
- * 用户ID
- *
- * @var int
- */
- protected $userId;
- /**
- * 构造函数
- *
- * @param int $userId 用户ID
- */
- public function __construct(int $userId)
- {
- $this->userId = $userId;
- }
- /**
- * 上传图片
- *
- * @param UploadedFile $file 上传的文件
- * @param bool $private 是否私有
- * @return FileImg 图片模型
- * @throws \Exception 上传失败时抛出异常
- */
- public function uploadImg(UploadedFile $file, $private = false)
- {
- $dirLogic = new DirLogic();
- $dir = $dirLogic->getDir($this->userId);
- // 重绘
- $upfilepath = $file->getRealPath();
- // create image manager with desired driver
- $manager = new ImageManager(new Driver());
- // read image from file system
- $image = $manager->read($upfilepath);
- // resize image proportionally
- $image->scale($image->width(), $image->height());
- $path = $dir . '/' . uniqid() . '.webp';
- // save modified image in new format
- $webpimg = $image->toWebp();
- $fileString = $webpimg->toString();
- $size = $webpimg->size();
- // 保存
- $disk = StorageConfig::getStorage();
- $res = Storage::disk($disk)->put($path, $fileString);
- if ($res === false) {
- throw new \Exception('服务器错误,请联系客服.');
- }
- $f = new FileImg();
- $f->storage_disk = $disk;
- $f->path = $path;
- $f->user_id = $this->userId;
- $f->o_name = $file->getClientOriginalName();
- $f->type1 = 'webp';
- $f->fsize = $size;
- $f->private = (int)$private;
- $f->re_id = 0;
- $f->re_type = '';
- $f->save();
- $f->refresh();
- return $f;
- }
- }
|