我有一个代码来上传文件,并使用html5 chunking来切片文件。目前,进度条适用于每个文件块,我应该怎么做才能使它只有一个进度条,但对于所有块的响应。例如代码和图片:每个进度条对应一个文件块(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);
}
答案 0 :(得分:0)
您必须保留一个全局变量,该变量包含到目前为止的总上传字节数,并在进度处理程序中更新它。
var totalLoaded = 0
内部uploadFile()
:
var chunkLoaded = 0;
....
function(e) {
var prevLoaded = chunkLoaded;
if (e.lengthComputable) {
// use e.loaded and e.total as a percentage of bytes per chunk
// upload request contains more bytes than the actual chunk
chunkLoaded = Math.ceil(e.loaded / e.total * BYTES_PER_CHUNK);
totalLoaded = totalLoaded - prevLoaded + chunkLoaded;
// update progress bar here
}
}
是的,您是否同时上传了20个块?这通常不是非常健康,并且容易丢失连接(如果您希望重试块,则必须更新totalLoaded
。)
最好将并发上传者的数量限制为2/3。