我有一个进度条,它会随着文件的数量和大小而增加。
我想在使用 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) { ... }
});
}
最佳答案
如果你想显示每个文件上传的百分比没有错,那么看看这个
<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);
}
}
关于javascript - 使用 HTML5 通过 AJAX 上传一些文件时的整体进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30452396/