sunrise's avatar

laravel can not "move()" file

I am using Laravel 5.3.

And I use cropper https://github.com/fengyuanchen/cropper to crop image and then upload it to back end via ajax.

    $('#uploadAvatar').on('click', function (e) {

        $("#image").cropper('getCroppedCanvas').toBlob(function (blob) {
            var formData = new FormData();

            formData.append('croppedImage', blob);

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                type: "POST",
                url: "{{ url('/change-avatar') }}",
                processData: false,
                contentType: false,
                data: formData
            }).done(function (response) {
                //...
            }).fail(function (data) {
                //...
            });
        });
    });

the headers of ajax request is like this: enter image description here

Laravel get the image and do something like this:

    public function changeAvatar (Request $request)
    {
        $file = $request->croppedImage;
        $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()
            ]);
    
        }
    
        $destinationPath = '/images/uploads/';
        $user=\Auth::user();
        $fileName = $user->id . '_' . time() . '.'.$file->clientExtension();
        $file->move($destinationPath, $fileName);
        //dd($file);
        $user ->avatar = $destinationPath.$fileName;
        $user ->save();
    
        return \Response::json([
            'success'=>true,
            'avatar'=>asset($destinationPath.$fileName),
        ]);
    
    }

In above method, the line $file->move($destinationPath, $fileName); not working.

Why is it?

0 likes
2 replies
jlrdw's avatar

In your ajax you have a - change-avatar in method no - public function changeAvatar (Request $request)

Snapey's avatar

How do you know its not working?

Also, remember that you are dealing with the file system here /images/ is in the root of your file system, not the root of your web server.

try

$destinationPath = public_path() . '/images/uploads/';

1 like

Please or to participate in this conversation.