Reputation: 4232
I'm using Laravel 5.3
,
I crop a image with javascript and upload it with ajax.
The cropped image is changed to a blob file when uploading.
But in backend,How to check the blob file is a image?
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),
]);
}
the file is a image,but the error is always like this:
{"success":false,"errors":{"image":["image must be an image."]}}
Upvotes: 0
Views: 3289
Reputation: 8069
Try this if this work:
After you write the blob into the destination path, do this:
//...
$file = file_put_contents($destinationPath.$fileName, $blob);
$uploadedFile = new \Illuminate\Http\UploadedFile($file, "dummy");
$input = array('image' => $uploadedFile);
//...
Laravel's image validation requires the file to be an instance of UploadedFile to be able to pass the validation.
Upvotes: 1
Reputation: 1320
You could test the contents of the blob, using a first-bits test.
This way, there is no need to first upload the file to the filesystem, and removing later.
It's explained here: answer
Upvotes: 1