【问题标题】:javascript how to make a progress bar for each filejavascript如何为每个文件制作进度条
【发布时间】:2014-01-19 09:48:44
【问题描述】:

我写了一个纯 javascript ajax 上传器。

在这里您可以看到附加到元素的progress event。如何遍历文件数组,然后为每个数组显示一个进度条?

这是处理进度事件的代码部分:

`request.upload.addEventListener('progress', function(event){ var progress = document.getElementById('progressBar');

    if(event.lengthComputable)
    {                       

        // get the loaded amount in decimals. For instance: if 50kbs of a 100kbs file is loaded, it equals 0.5
        var percent = event.loaded / event.total;

        // now fill in the progressBar div with a dynamic percentage change. 
        if(progress.hasChildNodes())
        {
            progress.removeChild(progress.firstChild);  
        }

        progress.appendChild(document.createTextNode(Math.round(percent*100)+" %")); // this converts the decimals to a integer number between 0-100 representing the percentage. 
    }`

这是我的文件数组(我需要为用户选择的每个文件创建一个单独的进度条,因为此上传允许选择多个文件):

var file = document.getElementById('file');

    // assigning a new FormData
    var data = new FormData();

    // now append selected files to the data object
    for(var i = 0; i < file.files.length; ++i)
    {
        // append each file to the data object
        data.append('file[]', file.files[i]);   
    }

【问题讨论】:

  • 我已经编辑了帖子。 file[]输入的文件数组

标签: javascript ajax progress


【解决方案1】:

不要为每个进度更新删除/创建。只需更改 div 的宽度即可显示进度:

<div style="border:1px solid #000;background-color:#fff;width:200px;">
    <div id="progress" style="width:0%;"></div>
</div>

现在在进度事件上,只是改变了 $("#progress") 的宽度 %。或者,如果您显示字符串“65% done”,则只需替换它的 innerHTML

【讨论】:

  • 请看一下引用文件数组的帖子的编辑版本
【解决方案2】:

对于 i 的每个值,创建进度指示器的副本并将其放入数组中,使其位于位置 i。如果您在需要更新时不知道索引,请使用对象或为它们提供 ID,以便您找到正确的更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多