laravel 上传图片
laravel 上传图片
图片表
//Picture
protected $fillable = [
'picture_category',//所属分类
'picture_name',//图片名称
'picture_path',//图片地址
'created_at',
'updated_at',
];
代码
class UploadBiz extends BaseBiz
{
public function __construct()
{ }
public static $PictureTypeAllow = ['image/jpeg', 'image/png', 'image/gif'];
public $pictureMaxSize = 5; //单位m
public function picture($request)
{
if (!$request->hasFile('picture')) {
return $this->responseInvalidParams();
}
$picture = $request->file('picture');
if($request->has('type') && $request->has('type') == 'front'){
$pictureMaxSizeTrans = trans('validation.picture_max_size');
$pictureTypeTrans = trans('validation.picture_type');
$pictureInvalidTrans = trans('validation.picture_invalid');
$operateFailTrans = trans('operate.fail');
$uploadFailTrans = trans('operate.upload_fail');
}else{
$pictureMaxSizeTrans = self::trans('validation.picture_max_size');
$pictureTypeTrans = self::trans('validation.picture_type');
$pictureInvalidTrans = self::trans('validation.picture_invalid');
$operateFailTrans = self::trans('operate.fail');
$uploadFailTrans = self::trans('operate.upload_fail');
}
//判断大小
if ($picture->getClientSize() > $this->pictureMaxSize * 100 * 1024) {
return $this->responseInvalidParams($pictureMaxSizeTrans . $this->pictureMaxSize . '00kb');
}
//判断图片类型
if (array_search($picture->getMimeType(), self::$PictureTypeAllow) === false) {
return $this->responseInvalidParams($pictureTypeTrans);
}
if (!$picture->isValid()) {
return $this->responseInvalidParams($pictureInvalidTrans);
abort(400, '无效的上传文件');
}
// 文件名
//$fileName = $picture->getClientOriginalName();
$extension = $picture->getClientOriginalExtension(); //获得上传文件扩展名
// 生成新的统一格式的文件名
$newPictureName = date('His') . '-' . mt_rand(1000, 9999) . '.' . $extension;
// 图片保存路径
$savePath = 'images/' . date('Ym');
Storage::disk('public')->makeDirectory($savePath);
$filePath = $savePath . '/' . $newPictureName;
$data['picture_name'] = $newPictureName;
$data['picture_path'] = Storage::url($filePath);
$data['picture_category'] = $request->input('picture_category');
if (empty($data['picture_category'])) $data['picture_category'] = 0;
//判断文件是否存在数据库
$pictureInfo = Picture::where('picture_path', $data['picture_path'])
->where('picture_category', $data['picture_category'])
->first();
if ($pictureInfo) {
return $this->responseSuccessForIE($data);
}
try {
// 将文件保存到本地时,先判断同名文件是否已经存在,如果存在直接返回
if (!Storage::disk('public')->has($filePath)) {
if ($picture->storePubliclyAs($savePath, $newPictureName, ['disk' => 'public'])) { } else {
return $this->responseInvalidParams($uploadFailTrans);
}
}
$pictureObj = Picture::create($data);
$data['id'] = $pictureObj->id;
return $this->responseSuccessForIE($data);
} catch (\Exception $e) {
\Log::error('操作失败:'.$e->getMessage(),$request->all());
return $this->responseInvalidParams($operateFailTrans);
}
}
}
请求
参数名 | 必选 | 类型 | 说明 |
---|---|---|---|
picture | 是 | file | 图片文件 |
picture_category | 否 | int | 所属分类 |