dongmei8460
2014-02-06 17:33
浏览 73

AJAX上传显示多个文件上传中仅最后一个元素的进度

I have this code

for(var i=0; i<ObjectMover.length; i++)
{
    var formdata = new FormData();
    formdata.append("fl", ObjectMover[i]);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", function(ev) 
    {
        if(ev.lengthComputable) 
        {
             $('#pb'+i).css('width', (ev.loaded / ev.total) * 100 + "%");
        }
    }, false);
    ajax.open("POST", "file_upload.php");
    ajax.send(formdata);
}

this code is working fine but the problem is that when I upload multiple files say 3 files then it shows only the progress of 3rd upload. While it is uploading all files to the server but shows the progress of only last file. I checked by putting console.log(i); in progress event like

    ajax.upload.addEventListener("progress", function(ev) 
    {
        if(ev.lengthComputable) 
        { 
                         console.log(i);
             $('#pb'+i).css('width', (ev.loaded / ev.total) * 100 + "%");
        }
    }, false);

Console shows only last file number (3). Why? Where am I making mistake. While I have same code in other file and that works good with same as above code. With my above code, there becomes 3 progress bars for each file individually but only last (3rd) progress bar shows progress of 3rd file. I checked all my "error", "load", "progress" and "abort" events if there was error from any of them but not at all. Even all upload requests are giving message on "load" event.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyaobo9081 2014-02-06 18:20
    已采纳

    Problem

    That's simple because in your code

      $('#pb'+i).css('width', (ev.loaded / ev.total) * 100 + "%");
    

    i is set to the length of your total files as of your for loop and therefore it simply give width to your i progress bar and that's last one no matter which progress event is responsing.

    Solution

    instead of sending files from a single loop send your files from another loop calling your upload function from that loop giving your file as parameter in it. Something similar to this

    function UploadMyFilesQueue()
    {
        for(var i=0; i<files.length; i++)
        {
              UploadThisFile(files[i], i);
        }
    }
    
    function UploadThisFile(file, pbid)
    {
        var formdata = new FormData(); 
        formdata.append("fl", file);
        var ajax = new XMLHttpRequest();
        ajax.send(formdata);
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题