0

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."]}}
UmAnusorn
  • 10,420
  • 10
  • 72
  • 100
zwl1619
  • 4,002
  • 14
  • 54
  • 110

2 Answers2

1

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.

Lionel Chan
  • 7,894
  • 5
  • 40
  • 69
  • ErrorException in UploadedFile.php line 88: Missing argument 2 for Symfony\Component\HttpFoundation\File\UploadedFile::__construct(), called in D:\wnmp\www\laravel-5-3-dev\app\Http\Controllers\UsersController.php on line 28 and defined – zwl1619 Nov 04 '16 at 13:55
  • I'm sorry. Argument two is "originalName". Supply a dummy string should be fine. – Lionel Chan Nov 04 '16 at 16:19
1

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

Community
  • 1
  • 1
Jan Willem
  • 1,280
  • 1
  • 9
  • 9