【问题标题】:Multiple progress bar status with one XMLHttpRequest一个 XMLHttpRequest 的多个进度条状态
【发布时间】:2021-02-11 16:17:45
【问题描述】:

尝试通过一个带有多文件上传的 XMLHttpRequest 获取多个进度条状态。无法使用 jQuery,并且由于客户端限制,我没有选项循环文件并在循环中包含 new XMLHttpRequests

目前我可以为所有文件组合一个进度条。我需要的是多个进度条百分比。如果我在 fileObj 循环中执行 request.upload.onprogress,那么只会更新最后一个进度条。

let formData = new FormData(); 
let request = new XMLHttpRequest();
request.open('POST', postUrl);

for( var x in fileObj){
    formData.append("file", fileObj[x]);

    //this is where I tried to put the request.upload.onprogress with dynamic ids but failed.
}

request.upload.onprogress = function (e) {
    if (e.lengthComputable) {
    var percentComplete = (e.loaded / e.total) * 100;
    d.getElementById("progress-bar" ).style.width = percentComplete + "%";
    d.getElementById('progress-bar-output').innerHTML = Math.round(percentComplete) + "%";              
    }
};

request.onload = function (e) {
    console.log( JSON.parse( e.target.response ) );
};

request.send(formData);

【问题讨论】:

  • 单个 XHR 有一个进度 - 您可以计算每个文件的上传长度,这样您就可以计算单个进度
  • fileObj FileList 对象吗?

标签: javascript xmlhttprequest


【解决方案1】:

如果fileObjFileList 对象,您可以执行以下操作

let formData = new FormData(); 
let request = new XMLHttpRequest();
let info = [];
let acc = 0;
request.open('POST', postUrl);

for (let x in fileObj){
    const file = fileObj[x];
    formData.append("file", file);

    const cutoff = acc += file.size;
    const index = info.length;
    info.push({cutoff, size: file.size, name: file.name, index});
}


request.upload.addEventListener('progress', function (e) {
    if (e.lengthComputable) {
        const percentComplete = (e.loaded / e.total) * 100;
        d.getElementById("progress-bar" ).style.width = percentComplete + "%";
        d.getElementById('progress-bar-output').innerHTML = Math.round(percentComplete) + "%";
        //
        // 
        const file = info.find(({cutoff}) => cutoff <= e.loaded);
        const thisPercentage = 100 * (e.loaded - (file.cutoff - file.size)) / file.size;
        // display file progress here
        // useful info: file.index - i.e. you could show `Uploading File ${file.name} ... ${file.index + 1} of ${info.length}`
    }
});

request.addEventListener('load', function (e) {
    console.log( JSON.parse( e.target.response ) );
};

request.send(formData);

【讨论】:

    猜你喜欢
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    相关资源
    最近更新 更多