61 lines
1.6 KiB
PHP
Executable File
61 lines
1.6 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Service;
|
|
|
|
use App\Enums\MaterialScene;
|
|
use App\Enums\UserType;
|
|
use App\Model\Material;
|
|
use App\Utils\ThrowException;
|
|
use Illuminate\Http\UploadedFile;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
class MaterialService
|
|
{
|
|
public static function enableUploadExt()
|
|
{
|
|
return [
|
|
'jpg', 'png', 'jpeg', 'gif', 'tiff'
|
|
];
|
|
}
|
|
|
|
public static function maxUploadSize()
|
|
{
|
|
return 1024 * 1024 * 10;
|
|
}
|
|
|
|
public function upload(UploadedFile $file, $userId, $scene, $userType = UserType::SELLER)
|
|
{
|
|
ThrowException::isTrue(!$file, '请选择文件');
|
|
if (!$file->isValid()) {
|
|
Log::error('上传文件,校验失败', [
|
|
'error' => $file->getErrorMessage(),
|
|
'user_id' => $userId,
|
|
'userType' => $userType
|
|
]);
|
|
ThrowException::run('文件无效');
|
|
}
|
|
|
|
// 文件类型
|
|
$fileType = explode("/", $file->getClientMimeType())[0];
|
|
$ext = $file->getClientOriginalExtension();
|
|
|
|
ThrowException::isTrue(!in_array(strtolower($ext), self::enableUploadExt()), '该文件不支持上传');
|
|
|
|
ThrowException::isTrue($file->getSize() > self::maxUploadSize(), "文件大小不能超过10M");
|
|
|
|
|
|
$scenePath = MaterialScene::getDiskPath($scene);
|
|
|
|
$path = Storage::disk('local')->put($scenePath, $file);
|
|
|
|
$m = new Material();
|
|
$m->scene = $scene;
|
|
$m->user_id = $userId;
|
|
$m->user_type = $userType;
|
|
$m->path = '/uploads/' . ltrim($path, '/');
|
|
$m->save();
|
|
return $m;
|
|
}
|
|
}
|