我有一个多文件上传表单:
<input type="file" name="files" multiple />
我正在使用 ajax 发布这些文件。我想一个一个上传选定的文件(以创建单独的进度条,并且出于好奇)。
我可以通过以下方式获取文件列表或单个文件
FL = form.find('[type="file"]')[0].files
F = form.find('[type="file"]')[0].files[0]
一灵
FileList { 0=File, 1=File, length=2 }
File { size=177676, type="image/jpeg", name="img.jpg", more...}
但是 FileList 是不可变的,我不知道如何提交单个文件。
我认为这是可能的,因为我看到了http://blueimp.github.com/jQuery-File-Upload/ .我不想使用这个插件,因为它与结果一样重要(而且它需要太多的自定义)。我也不想使用 Flash。
最佳答案
要使其成为同步操作,您需要在完成最后一个传输后开始新的传输。例如,Gmail 会同时发送所有内容。
AJAX 文件上传进度事件是 progress
或 onprogress
关于原始XmlHttpRequest
实例。
所以,在每个 $.ajax()
之后,在服务器端(我不知道您将使用什么),发送一个 JSON 响应以在下一个输入上执行 AJAX。一种选择是将 AJAX 元素绑定(bind)到每个元素,以使事情变得更容易,因此您可以在 success
中这样做$(this).sibling('input').execute_ajax()
.
像这样:
$('input[type="file"]').on('ajax', function(){
var $this = $(this);
$.ajax({
'type':'POST',
'data': (new FormData()).append('file', this.files[0]),
'contentType': false,
'processData': false,
'xhr': function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', progressbar, false);
}
return xhr;
},
'success': function(){
$this.siblings('input[type="file"]:eq(0)').trigger('ajax');
$this.remove(); // remove the field so the next call won't resend the same field
}
});
}).trigger('ajax'); // Execute only the first input[multiple] AJAX, we aren't using $.each
以上代码适用于多个 <input type="file">
但不适用于 <input type="file" multiple>
,在这种情况下,它应该是:
var count = 0;
$('input[type="file"]').on('ajax', function(){
var $this = $(this);
if (typeof this.files[count] === 'undefined') { return false; }
$.ajax({
'type':'POST',
'data': (new FormData()).append('file', this.files[count]),
'contentType': false,
'processData': false,
'xhr': function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', progressbar, false);
}
return xhr;
},
'success': function(){
count++;
$this.trigger('ajax');
}
});
}).trigger('ajax'); // Execute only the first input[multiple] AJAX, we aren't using $.each
关于jquery - HTML5 多文件上传 : upload one by one through AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13656066/