dongmei8460 2014-02-06 17:33
浏览 75
已采纳

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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启