0

I am using laravel 5. I have did the following code to post data using json to my controller. But I cannot make file uploading by this manner.

e.preventDefault();
$.ajax({
    type: 'POST',
    cache: false,
    dataType: 'JSON',
    url: 'tasks',
    data: $('#my_form').serialize(),
    success: function(data) {
        console.log(data);
    },
});

I have the following html code to upload files.

<input type="text" name="name" value="" />
<input type="text" name="name" value="" />
<input type="file" class="form-control" name="documents[]" multiple>

How can I send file using json in laravel? I have did many search but I cant get proper solution

Praveen Srinivasan
  • 1,562
  • 4
  • 25
  • 52

2 Answers2

1

Use this as your code:

e.preventDefault();
var mydata = new FormData($('#my_form')[0]);
$.ajax({
    type: 'POST',
    cache: false,
    dataType: 'JSON',
    url: 'tasks',
    data: mydata,
    processData: false,
    contentType: flase
    success: function(data) {
        console.log(data);
    },
});

Note that this doesn't work on some older browsers such as IE 9 or older so you might need to disabled this feature to prevent your errorlogs from overloading, I give my users a custom message that the feature is disabled in older browsers by using

if(typeof FormData !== 'undefined'){
   var formdata = new FormData($("#documentform")[0]);
}
else{
   $("#errormsg").val("upload feature is disabled in this browser version");
   return false;
}
Jeremy C.
  • 2,405
  • 1
  • 12
  • 28
0

The standard jquery ajax don't support directly the sending of files. To do it, you basicly need too use the FormData object instead of a standard js one for your post parameter collection.

You will also need to disable 2 parametters in the ajax option :

processData: false,
contentType: false,

to prevent jquery from interfering with the FormData Object.

More info here : https://stackoverflow.com/a/8244082/4734683

Community
  • 1
  • 1
Remy Grandin
  • 1,638
  • 1
  • 14
  • 34