我有一个进度条,根据文件数量和大小增加。
我希望在使用AJAX和HTML5在服务器上上传文件时显示整体进度条。
我将每个文件上传到服务器并增加进度条。但我不知道如何。
所以,javascript代码:
$("#add-files").on("change", function(){
var files = $(this).prop("files");
$.each(files, function(index, file) {
var formData = new FormData();
formData.append("FileName", file.name);
formData.append("FileSize", file.size);
uploadOnServer(formData);
});
});
function uploadOnServer(formData) {
var xmlHttpRequest = new XMLHttpRequest();
if (xmlHttpRequest.upload) {
xmlHttpRequest.upload.addEventListener("progress", function(evt) {
if(evt.lengthComputable) {
var percent = 100 * (evt.loaded / evt.total);
// update progress bar
}
});
}
$.ajax({
url: "test/test",
type: "POST",
data: formData,
processData: false,
xhr: function() { return xmlHttpRequest; },
success: function(result) { ... }
});
}
答案 0 :(得分:3)
如果没有错,你想显示上传的每个文件的百分比,那么看看这个
<div id="#statustxt_n">0%</div>
function uploadFile(file) {
var formData = new FormData();
formData.append('file', $('#add-files')[0].files[0]);
$.ajax({
type: 'post',
url: 'test/test',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
//update progressbar percent complete
statustxt1.html('0%');
// For handling the progress of the upload
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
data: formData,
success: function (status) {
alert("Success")
},
processData: false,
contentType: false
});
}
function progressHandlingFunction(e)
{
if(e.lengthComputable){
var percentage = Math.floor((e.loaded / e.total) * 100);
//update progressbar percent complete
statustxt1.html(percentage + '%');
console.log("Value = "+e.loaded +" :: Max ="+e.total);
}
}
答案 1 :(得分:0)
我之前没有做过这种进度条,所以下面只是一个伪代码/一个想法,你可以尝试。
首先,定义一个包含所有xmlHttpRequest对象的全局数组。
var loadingXhrRequests = [];//<--push all xhr requests here
然后。无论何时开始新的上传,都要创建xhr请求并将其推入阵列。
//go over all xhrRequests, and add the total loaded and total to load
var globalUpdateProgress() {
var i, xhr, loaded = 0, total = 0, xhr;
for (i = 0; i < loadingXhrRequests.length; i++) {
xhr = loadingXhrRequests[i];
if (xhr.total && xhr.loaded) {total+=xhr.total;loaded += xhr.loaded;}
}
return (100 * (loaded / total));
}
var xhr = new XMLHttpRequest();
loadingXhrRequests.push(xhr);
var xhr2 = new XMLHttpRequest();
loadingXhrRequests.push(xhr2);
//start uploading using xhr and xhr2 ... or more.
然后,每当从任何xhr对象获得进度更新时,就会调用通过该数组的共享updateProgress函数,并检查所有xhr对象的进度。还将最后加载的事件/总值存储在xhr中,以便稍后访问。
xhr.upload.addEventListener("progress", function(evt) {
if(evt.lengthComputable) {
var percent = 100 * (evt.loaded / evt.total);
xhr.loaded = evt.loaded;
xhr.total = evt.total;
//note - check that you dont overwrite any important properties of xhr
// update progress bar
globalUpdateProgress();//<- call this in all individual xhr progress callback
}
});