Reputation: 677
I need to upload multiple files but one each time asynchronous and show progress for each file. For each file i use separate progress bar with class name according to the list index (ie uploadprogress0,uploadprogress1) my code is this:
var i=0
var formData = new FormData();
formData.append('files[]', toUpload[i]);
ajaxloopreq(formData);
var ajaxloopreq = function (formData) {
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
var percentComplete = e.loaded / e.total;
elem.find('.uploadprogress' + i).css({
width: percentComplete * 100 + '%'
});
}
}, false);
return xhr;
},
async: true,
type: 'POST',
data: formData,
cache:false,
contentType: false,
processData: false,
url: '',
success:function(data){
//do something
}
})
i++;
if (i <toUpload.length) {
var formData = new FormData();
formData.append('files[]', toUpload[i]);
ajaxloopreq(formData);
}
}
the result of that is the progress goes only in the last uploadprogress div as a result the progress goes like crazy (parallels progress). Any idea how to fix it?
Upvotes: 0
Views: 1311
Reputation: 9929
This is because your upload progress is asynchronous and you variable 'i' is incremented synchronous. So by the time your first file is uploaded the value of 'i' is already equal to the length of the total amount of files.
You can probably fix it by passing along the index with the call to ajaxloopreq:
ajaxloopreq(formata, i);
And use that to find the correct div.
Upvotes: 1