0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you!! That fix my problem!
No problem. Hope my answer also gave insight it what was the actual problem you where having?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.