Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS:How to send multiple files using FormData(jQuery Ajax)

In my form multiple file uploads are there,using FormData only one file is uploading ,though I'm selecting more than one file to upload,following is the code

HTML

<form name="uploadImages" method="post" enctype="multipart/form-data">
<input type="file" name="photo[]" value="">
<input type="file" name="photo[]" value="">
<input type="file" name="photo[]" value="">
</form>

JS

     var ajaxData = new FormData();
     ajaxData.append( 'action','uploadImages');
     jQuery.each($("input[name^='photo']")[0].files, function(i, file) {
        ajaxData.append('photo['+i+']', file);
      });
     $.ajax({
        url: URL,
        data: ajaxData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        dataType:'json',
        success: function(data) {
            if (data.status == 'success') {
                location.reload();
            }
        }
       });

I'm using PHP at server,using HTML attribute name i,e photo only I'm able to save files,dynamic file names won't be work for me.

like image 544
Mahesh.D Avatar asked May 11 '13 11:05

Mahesh.D


People also ask

How do I pass multiple files in FormData?

Uploading Multiple Files const uploadFile = (files) => { console. log("Uploading file..."); const API_ENDPOINT = "https://file.io"; const request = new XMLHttpRequest(); const formData = new FormData(); request. open("POST", API_ENDPOINT, true); request. onreadystatechange = () => { if (request.

How can add multiple form data using jquery Ajax?

For Sending or inserting or saving multiple data in single click then you have to use Jquery and javascript code. By using Jquery or Javascript code you can generate dynamic HTML field in your HTML form. We can generate any dynamic HTML field by using Jquery and append into your form fields.

How use Enctype multipart form data in Ajax?

2.1 Create a Javascript FormData object from a form. $. ajax({ type: "POST", enctype: 'multipart/form-data', processData: false, // Important!

How do I send multiple files in FormData in react?

How to Upload Multiple Files in React using FormData. When we need to upload multiple files using Fetch, we have to use a new type of object called FormData. FormData allows us to append multiple key/value pairs onto the object. After we're done appending, we then pass it to the POST request's body.


1 Answers

You have an error in javascript: you're iterating only over files in one input please have a look at this

var ajaxData = new FormData();
ajaxData.append( 'action','uploadImages');
$.each($("input[type=file]"), function(i, obj) {
        $.each(obj.files,function(j, file){
            ajaxData.append('photo['+j+']', file);
        })
});

example on jsfiddle

like image 78
Yuriy Avatar answered Oct 18 '22 21:10

Yuriy