get all files from multiple input

Asked by At

What I want is to save all images from multiple inputs. But I am having a hard time of getting all images without using form submit. Am using ajax.

This is my HTML for example

<input type="file" id="image-1" name="item_file[]">
<input type="file" id="image-2" name="item_file[]">

And This is my ajax when submit

var file_data = $("#image")[0].files; 
var form_data = new FormData();
for(var i = 0; i < file_data.length; i++) {
   form_data.append('item_file[]', file_data[i]);;
}

 $.ajax({
    url: "upload.php",
    dataType: 'json',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data,       
    type: 'POST'
 })

In my server side I only got 1.

1 Answers

0
adeneo On Best Solutions

First of all, you can't use the same ID twice, you should change it

<input type="file" id="image1" class="image" name="item_file[]">
<input type="file" id="image2" class="image" name="item_file[]">

Secondly, by using $("#image")[0] you only get the first one, you have to iterate over the elements

var form_data = new FormData(), k = 0;

$('.image').each(function(_, elem) {
    var images = elem.files;

    for(var i=0; i < images.length; i++) {
        form_data.append("image" + (++k), images[i]);
    }
});

$.ajax({
    url         : 'upload.php',
    data        : form_data,
    processData : false,
    contentType : false,
    type: 'POST'
}).done(function(data){
    // do stuff
});