最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiple files on FormData() append - Stack Overflow

programmeradmin2浏览0评论

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 the multiple 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
Add a ment  | 

2 Answers 2

Reset to default 4

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)
})

Try

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

评论列表(0)

  1. 暂无评论