我有一个上传文件的代码,并使用 html5 分块来切片文件。目前,进度条适用于每个文件块,我应该怎么做才能使它只有一个进度条,但要响应所有块。例如示例代码和图片:每个进度条对应一个文件块(1MB),但如何将这些进度条组合成只有 1 个条但仍然是正确的百分比等
var uploaders = [];
var totalChunks = 0;
var i = 0;
$(document).ready(function() {
var progress = document.querySelector('progress');
var bars = document.querySelector('#bars');
});
//function for after the button is clicked, slice the file
//and call upload function
function sendRequest() {
//clean the screen
//bars.innerHTML = '';
var blob = document.getElementById('fileToUpload').files[0];
var originalFileName = blob.name;
const BYTES_PER_CHUNK = 1 * 1024 * 1024; // 10MB chunk sizes.
const SIZE = blob.size;
var start = 0;
var end = BYTES_PER_CHUNK;
totalChunks = Math.ceil(SIZE / BYTES_PER_CHUNK);
while( start < SIZE ) {
if (blob.webkitSlice) {
var chunk = blob.webkitSlice(start, end);
} else if (blob.mozSlice) {
var chunk = blob.mozSlice(start, end);
}
uploadFile(chunk, originalFileName, totalChunks);
start = end;
end = start + BYTES_PER_CHUNK;
}
}
function uploadFile(blobFile, fileName, totalChunks) {
var progress = document.createElement('progress');
progress.min = 0;
progress.max = 100;
progress.value = 0;
bars.appendChild(progress);
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php"+"?"+"file="+fileName + i, true);
i++;
xhr.onload = function(e) {
//make sure if finish progress bar at 100%
progress.value = 100;
//counter if everything is done using stack
uploaders.pop();
if (!uploaders.length) {
bars.appendChild(document.createElement('br'));
bars.appendChild(document.createTextNode('DONE :)'));
mergeFile(fileName, totalChunks);
}
};
// Listen to the upload progress for each upload.
xhr.upload.onprogress = function(e) {;
if (e.lengthComputable) {
progress.value = (e.loaded / e.total) * 100;
}
};
uploaders.push(xhr);
xhr.send(fd);
}