我遇到了同样的问题,使用了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
}
});
然后,当你有文件清单对象数组,你可以形成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/