對於這是一個同步操作,您需要在最後一個完成,開始新的傳遞。例如,Gmail可以同時發送所有內容。 對AJAX的文件上傳進度的事件是對原始XmlHttpRequest
實例progress
或onprogress
。
因此,在每個$.ajax()
之後,在服務器端(我不知道你將使用什麼),發送一個JSON響應來在下一個輸入上執行AJAX。一種選擇是對AJAX元素結合到每一個元素,使事情變得更容易,所以你可以只執行,在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
注意,此代碼是用於支持FORMDATA和XMLHttpRequest2中唯一的,舊的瀏覽器 – pocesar
沒有黑客不知道爲什麼它看起來那麼好吃......真是的現代瀏覽器;) – Selosindis
創建一個新的「形式」,並加入使用'(新的FormData())。append('file',this.files [count])''一個接一個的文件是我一直在尋找的,謝謝! – Mark