I have done some code to upload multiple files from browser to server, while showing progressbars as well. XHR2 send calls are asynchronous. The problem is that I want to call some functions after all the XHR2 send calls are finished.
Here is a very simplified snippet of my code:
<input id="upload" multiple="multiple" />
<script>
var files = document.getElementById("upload").files;
for (var i = 0, length = files.length; i < length; i++) {
var file = files[i];
var uploadFunc = function (arg) {
return function () {
processXHR(arg);
};
}(file);
uploadFunc();
}
function processXHR(file) {
var normalizedFileName = getNormalizedName(file.name);
var url = 'upload_file/';
var formData = new FormData();
formData.append("docfile", file);
var xhr = new XMLHttpRequest();
var eventSource = xhr.upload;
eventSource.addEventListener("progress", function (evt) {
var position = evt.position || evt.loaded;
var total = evt.totalSize || evt.total;
console.log('progress_' + normalizedFileName);
console.log(total + ":" + position);
$('#progress_' + normalizedFileName).css('width', (position * 100 / total).toString() + '%');
}, false);
eventSource.addEventListener("loadstart", function (evt) {
console.log('loadstart');
}, false);
eventSource.addEventListener("abort", function (evt) {
console.log('abort');
}, false);
eventSource.addEventListener("error", function (evt) {
console.log('error');
}, false);
eventSource.addEventListener("timeout", function (evt) {
console.log('timeout');
}, false);
xhr.onreadystatechange = function (evt) {
if (xhr.readyState == 4) {
console.log('onreadystatechange: File uploaded.');
}
};
xhr.open('post', url, true);
xhr.send(formData);
}
</script>
Whenever "onreadystatechange: File uploaded." is printed in console, I know that one of the files is done uploading. But I am not able to write any code that will say "All Files uploaded.".
Thanks for any help. I am using jquery as well in case some one has a solution using jquery.