0
我需要一個進度條在我的文件上傳。這是Ajax調用我使用的文件上傳和進度條如何使用javascript和ajax調用將進度條添加到文件上傳?
$(function() {
$('button[type=button]').click(function(e) {
e.preventDefault();
//Disable submit button
$(this).prop('disabled',true);
var form = document.forms[0];
var formData = new FormData(form);
// Ajax call for file uploaling
var ajaxReq = $.ajax({
url : URI.file.multipleFileUploadUrl(),
type : 'POST',
data : formData,
cache : false,
contentType : false,
processData : false,
xhr: function(){
//Get XmlHttpRequest object
var xhr = $.ajaxSettings.xhr() ;
//Set onprogress event handler
xhr.upload.onprogress = function(event){
var perc = Math.round((event.loaded/event.total) * 100);
$('#progressBar').text(perc + '%');
$('#progressBar').css('width',perc + '%');
};
return xhr ;
},
beforeSend: function(xhr) {
//Reset alert message and progress bar
$('#alertMsg').text('');
$('#progressBar').text('');
$('#progressBar').css('width','0%');
}
});
// Called on success of file upload
ajaxReq.done(function(msg) {
$('#alertMsg').text(msg);
$('input[type=file]').val('');
$('button[type=submit]').prop('disabled',false);
});
// Called on failure of file upload
ajaxReq.fail(function(jqXHR) {
$('#alertMsg').text(jqXHR.responseText+'('+jqXHR.status+
' - '+jqXHR.statusText+')');
$('button[type=submit]').prop('disabled',false);
});
});
});
查找下面是文件上傳其正常工作沒有進度條整合。
function multipleFileUpload(form) {
var uploadSuccess = true;
var data = new FormData(form);
var csrf_headerName = $("meta[name='_csrf_header']").attr("content");
var csrf_paramValue = $("meta[name='_csrf']").attr("content");
ShowLoad();
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: URI.file.multipleFileUploadUrl(),
data: data,
beforeSend: function (request) {
request.setRequestHeader(csrf_headerName, csrf_paramValue);
},
processData: false,
contentType: false,
cache: false,
timeout: 6000000,
success: function (data) {
HideLoad();
data.forEach(function(d, index){
if(d.status === 'ERROR'){
// HideLoad();
uploadSuccess = false;
toastr.error('Error has occurred while uploading image file '+d.data.name);
}else if(d.data.id != null){
//HideLoad();
//toastr.success('Successfully updated '+d.data.name, 'Upload Success');
}
});
if(uploadSuccess){
mediaFileMetaDataSave(data[0],data[1]);
}
},
error: function (e) {
HideLoad();
toastr.error('Error has occurred while uploading attachments.');
}
});
}
,當我在我的腳本中使用上面的代碼,我可以做文件上傳正確雖然進度條立刻達到100%之前,文件上傳完畢。這裏有什麼問題?
好吧,讓我拿到我的採礦帽,鎬和火炬,並開始挖掘這個代碼堆。請更新並告訴我們確切的問題在哪裏 - > [mcve]。 – Mouser
我剛纔簡化了這個問題。請你現在看到它? – sndu
您是否在本地進行測試,文件上傳可能是即時的。 – Mouser