我遇到了同样的问题,使用了 Carrierwave,但我认为这并不重要,因为所有这些都是在客户端使用 jQuery 完成的。所以,我所做的是创建一个空数组:
data = [];
在文件输入更改时将上传的文件推送到数组:
$('#File-Upload input[type=file]').change(function(e){
var files = $('[type="file"]').get(0).files;
//checking if it was multiple files upload
if (!!$(this).prop('files') && $(this).prop('files').length > 1) { /
files_array = $(this)[0].files //creating array of uploaded files
$.each(files_array, function(indx, file){//iterate over this array, pushing files one by one
data.push(file)
})
}
else {
data.push($(this)[0].files[0]);// single file, just uploading
}
});
然后,当您拥有 FileList 对象数组时,您可以形成 FormData 对象并将其传递给提交,如下所示:
$(document).on('click', '.some-form input[type=submit]', function(e){
e.preventDefault();
formdata = new FormData();
$.each(data, function(i, file) {
formdata.append('files' + i, file);
});
//if you need to pass other parameters from your form you can do like this:
//var other_data = $('.some-form').serializeArray();
// $.each(other_data,function(key,input){
// formdata.append(input.name,input.value);
// });
// ... some ajax call goes here
});
这是小提琴:https ://jsfiddle.net/rp4kup3o/