Diego Vieira
Diego Vieira

Reputation: 199

Multiple files on FormData() append

I need to add an array of images in FormData, but only the first image is passing.

I know the problem is in the JS code because when I send the form direct to the php page, it works fine.

JavaScript

var url = $(this).attr('action');
var data = new FormData();

$.each($("input[type='file']")[0].files, function(i, file) {
    data.append('image[]', file);
});

$.ajax({
    url: url,
    type: 'POST',
    data: data,
    dataType: 'json',
    processData: false,
    contentType: false,
    success: function(data) {
        console.log(data);
    }
});

HTML

<label for="1">Image 1</label>
<input type="file" name="image[]" id="1"/>

<label for="1">Image 2</label>
<input type="file" name="image[]" id="2" />

<label for="1">Image 3</label>
<input type="file" name="image[]" id="3" />

Upvotes: 0

Views: 20567

Answers (2)

worrawut
worrawut

Reputation: 1068

For Vanilla JS, I like to use Array.from and loop through each element like this

let data = new FormData();
let input_file = document.querySelector('input[type="file"]')

Array.from(input_file.files).forEach((f) => {
    data.append('image[]', f)
})

Upvotes: 4

Vinay
Vinay

Reputation: 7676

Try

jQuery.each(jQuery('input[type=file]'), function(i, value) 
{
    data.append('image['+i+']', value.files[0]);
});

Upvotes: 0

Related Questions