我使用Laravel 5.3
,
我用javascript裁剪图像并用ajax上传。
裁剪后的图像在上传时将更改为blob文件。
但在后端,如何检查blob文件是一个图像?
public function changeAvatar(Request $request)
{
$user = 'Auth::user();
$blob = $request->croppedImage;
$destinationPath = 'images/uploads/';
$fileName = $user->id . '_' . time() . '.png';
$file = file_put_contents($destinationPath.$fileName, $blob);
$input = array('image' => $file);
$rules = array(
'image' => 'image'
);
$validator = 'Validator::make($input, $rules);
if ( $validator->fails() ) {
return 'Response::json([
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
]);
}
$user ->avatar = '/'.$destinationPath.$fileName;
$user ->save();
return 'Response::json([
'success'=>true,
'avatar'=>asset($destinationPath.$fileName),
]);
}
文件是一个图像,但错误总是这样:
{"success":false,"errors":{"image":["image must be an image."]}}
您可以使用首位测试来测试blob的内容。
这样,就不需要先将文件上传到文件系统,然后再删除。
说明如下:答案
如果可以的话试试这个:
将blob写入目标路径后,执行以下操作:
//...
$file = file_put_contents($destinationPath.$fileName, $blob);
$uploadedFile = new 'Illuminate'Http'UploadedFile($file, "dummy");
$input = array('image' => $uploadedFile);
//...
Laravel的图像验证要求文件必须是UploadedFile的一个实例才能通过验证