KAnouar
KAnouar

Reputation: 27

validate file uploaded by ajax in Laravel

i want to validate a file uploaded by AJAX in laravel, this is my code in my controller :

public function changePicture(Request $request)
{
     // get file : 
     $file = $request->file('image');

     $validator = Validator::make($request->all(), [
         'image' => 'image|mimes:jpg,jpeg,gif,png|max:2048'
     ]);

     if ($validator->fails())
          return response()->json(['is' => 'failed', 'error' => $validator->getMessageBag()]);

     return response()->json(['is'=>'success']);
}

but nothing happens when upload an incorrect file, but when upload a valid file, get the second response :

is:success .

my js code :

 $.ajax(
        {
            url: '/profile/change-picture',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            data: formData,
            mimeType: 'multipart/form-data',
            contentType: false,
            cache: false,
            processData: false,
            success: function (response){
                if(response.is === 'failed'){
                        $('.ui.modal').modal('show');
                }
            }
        });

but after waiting there is a error :

POST Content-Length of 20315736 bytes exceeds the limit of 8388608 bytes.

any idea !! thanks

Upvotes: 0

Views: 2681

Answers (2)

8388608 bytes is 8M, the default limit in PHP. Update your post_max_size in php.ini to a larger value.

upload_max_filesize sets the max file size that a user can upload while post_max_size sets the maximum amount of data that can be sent via a POST in a form.

So you can set upload_max_filesize to 1 meg, which will mean that the biggest single file a user can upload is 1 megabyte, but they could upload 5 of them at once if the post_max_size was set to 5.

Upvotes: 0

Christopher Francisco
Christopher Francisco

Reputation: 16278

Add these props to your ajax:

jQuery.ajax({
    ...
    contentType: false,
    processData: false,

Also, make sure your file is appended to the form data. There are plenty of ways to do that, here's one:

var data = new FormData();

jQuery.each(jQuery('#image')[0].files, function(index, file) {
    data.append('my-image-' + index, file);
});

About the error

Your webserver or PHP probably has a max upload file size. I suggest testing with a file lower than that value.

Upvotes: 2

Related Questions