I have recently developed a file upload script for my server.
My main objective is to enable support for multiple file uploads and chunking, especially since the files can vary in size from 5Mb to 2Gb.
The current obstacle I am facing involves all chunks of all files starting simultaneously once the upload process begins. This leads to browser lockup issues due to the limitation where Chrome allows only up to 6 requests per domain.
Below is the snippet of JavaScript code:
(function () {
'use strict';
var status = document.getElementById('status'),
uploaders = [],
upload,
chooseFile;
upload = function (blobOrFile, chunk_num, chunk_total, file_name) {
var uXHR;
uXHR = new XMLHttpRequest();
uXHR.open('POST', '/upload/url/', true);
uXHR.upload.onprogress = function (e) {
if (e.lengthComputable) {
console.log(Math.round((e.loaded / e.total) * 100));
}
};
uXHR.onloadend = function (e) {
uploaders.pop();
if (!uploaders.length) {
status.appendChild(document.createTextNode(' All Done! '));
allFilesUploaded(file_name, chunk_total);
}
};
uploaders.push(uXHR);
uXHR.send(blobOrFile);
};
chooseFile = document.getElementById('file-input');
chooseFile.addEventListener('change', function (e) {
var self = e.currentTarget;
var a;
for ( a=0; a<self.files.length; a++ ) {
var blob = self.files[a],
bytes_per_chunk,
SIZE,
num_chunks,
start,
end,
fileName;
fileName = self.files[a].name;
bytes_per_chunk = parseInt(67108864, 10); // 64mb
SIZE = blob.size;
num_chunks = Math.max(Math.ceil(SIZE / bytes_per_chunk), 1);
console.log('Sending' + num_chunks );
start = 0;
end = bytes_per_chunk;
var i = 1;
while (start < SIZE) {
upload(blob.slice(start, end), i, num_chunks, fileName);
start = end;
end = start + bytes_per_chunk;
i++;
}
}
}, false);
})();
Here is the basic HTML structure:
<input type="file" id="file-input" multiple="multiple" />
<p id="status"></p>
My goal is to establish a queue system for uploading chunks, with a maximum of 6 concurrent uploads running at any time.
In addition, I want to incorporate a callback function for when each file completes its upload, ideally with a global percentage completion feature. However, I am uncertain about how to implement this, especially since I have only been able to calculate progress for individual chunks.