简体   繁体   中英

jquery multiple ajax file upload loop async with multiple progressbar

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM