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" />
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" />
Share
Improve this question
asked Mar 2, 2018 at 0:22
Diego VieiraDiego Vieira
1991 gold badge6 silver badges15 bronze badges
2
-
Typo: by doing
$("input[type='file']")[0].files
you are iterating over all the files of the first input only ([0]
). What you want is$("input[type='file']").each(function(i, input) { $.each(input.files, function(j, file) {data.append...
Or, since none of your inputs has themultiple
attribute,$("input[type='file']").each(function(i, input) {data.append('image[]', input.files[0])})
– Kaiido Commented Mar 2, 2018 at 1:35 - Please check my updated answer – Vinay Commented Mar 3, 2018 at 1:31
2 Answers
Reset to default 4For 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)
})
Try
jQuery.each(jQuery('input[type=file]'), function(i, value)
{
data.append('image['+i+']', value.files[0]);
});