So I am using a ajax to upload multiple files. Everything seems to be working like a charm... I just can't get to make my progress bars to work ...
Any help would be really appreciated. Thanks.
var images = document.getElementById('images');
for(var i=0;i<images.files.length;i++) {
var formData = new FormData();
var image = images.files[i];
formData.append('image', image);
formData.append('order_id', document.getElementById('order_id').value);
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","/pictures/uploadImage");
xmlhttp.send(formData);
xmlhttp.upload.addEventListener('progress', function(e){
document.getElementById("image_"+i+"_progress").value = Math.ceil(e.loaded/e.total)*100;
}, false);
}
I am basically uploading images individually .. I figured that would help me track the progress bars better ... Perhaps there's another approach.
According to [MDN][1]:
Note: You need to add the event listeners before calling open() on the request. Otherwise the progress events will not fire.
So, combining this knowledge with Engin's answer, you could do like this:
const images = document.getElementById('images');
const completedCount = 0; // added for loadend scenario
const length = images.files.length;
for (let i = 0; i < length; i++) {
const formData = new FormData();
const image = images.files[i];
formData.append('image', image);
formData.append('order_id', document.getElementById('order_id').value);
const xmlhttp = new XMLHttpRequest();
(elId => {
xmlhttp.upload.addEventListener('progress', e => {
document.getElementById('image_' + elId + '_progress').value = Math.ceil(e.loaded / e.total) * 100;
}, false);
})(i); // to unbind i.
// --- added for loadend scenario. ---
xmlhttp.addEventListener('loadend', () => {
completedCount++;
if (completedCount == length) {
// here you should hide your gif animation
}
}, false);
// ---
xmlhttp.open('POST', '/pictures/uploadImage');
xmlhttp.send(formData);
}
To catch the event when all files are uploaded you may use loadend
events. I've updated my code (see comments), I'm not sure this is a correct way though.
[1]: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress