简体   繁体   English

FormData()上的多个文件追加

[英]Multiple files on FormData() append

I need to add an array of images in FormData, but only the first image is passing. 我需要在FormData中添加图像数组,但是只有第一个图像正在传递。

I know the problem is in the JS code because when I send the form direct to the php page, it works fine. 我知道问题出在JS代码中,因为当我将表单直接发送到php页面时,它可以正常工作。

JavaScript 的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 的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" />

Try 尝试

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

For Vanilla JS, I like to use Array.from and loop through each element like this 对于Vanilla JS,我喜欢使用Array.from并像这样遍历每个元素

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM