在 Laravel 5.4 ( Symfony )中,检测上传文件的扩展名
1、上传图片文件时报错,原因在于上传了 gif 格式的图片,当做了 JPEG 格式来处理。如图1
{ "code": 1, "message": "success", "result": "imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error: Not a JPEG file: starts with 0x47 0x49" }
2、查看相应代码实现。
public function upload(Request $request, StorageService $storageService) { $files = $request->files->all(); try { $logoImages = $storageService->storeAsTmpImage($files['upfile'], ['ext' => 'csv']); return $this->respondJson(['result' => $logoImages['url']]); } catch (\Exception $e) { return $this->respondJson(['result' => $e->getMessage(), 'code' => 1]); } }
3、决定在收到请求后,先判断一下文件的扩展名。参考网址:https://github.com/symfony/symfony/blob/3.0/src/Symfony/Component/HttpFoundation/File/UploadedFile.php 。返回原始文件扩展名。使用方法:getClientOriginalExtension() 。如图2
4、获取文件扩展名,转换为小写字母。再判断范围。相应代码实现。
public function upload(Request $request, StorageService $storageService) { $files = $request->files->all(); $extension = strtolower($files['upfile']->getClientOriginalExtension()); if (!in_array($extension, ['jpg', 'jpeg', 'png'])) { return $this->respondJson([ 'code' => 1, 'message' => '格式错误,仅支持PNG、JPG格式', ]); } try { $logoImages = $storageService->storeAsTmpImage($files['upfile'], ['ext' => 'csv']); return $this->respondJson(['result' => $logoImages['url']]); } catch (\Exception $e) { return $this->respondJson(['result' => $e->getMessage(), 'code' => 1]); } }
5、上传图片:2 – 副本.GIF,提示图片上传失败:格式错误,仅支持PNG、JPG格式,符合预期。提示信息有待于前端基于接口响应完善。如图3
{ "code": 1, "message": "格式错误,仅支持PNG、JPG格式" }
近期评论