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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?