javascript - XHR 带进度条的多文件上传

标签 javascript jquery file-upload xmlhttprequest progress-bar

我正在通过 input type="file"和 XHR 请求上传文件。上传进行得非常顺利。问题是,我无法使用 onprogress 更新我的进度条。如果我只上传一个文件,它会很好地工作,但由于有多个文件,只有一个进度条正在更新,其他的根本不起作用。它可能来自 for 循环,但我不知道如何我可能会解决这个问题如果有人有想法,那就太好了!

代码如下:

$('input').change(function() {

var allowedTypes = ['png', 'jpg', 'jpeg', 'gif'];   
var filesLen = this.files.length;
var fileInput = document.querySelector('#file');

for (i = 0; i < filesLen; i++)
{
    var vidType = this.files[i].name.split('.');

    if (allowedTypes.indexOf(vidType[vidType.length -1].toLowerCase()) != -1)
    {
        var progress = 'progress' + i;

        $('input').before('<p>' + this.files[i].name + ' <progress id="' + progress + '"></progress></p>');

        var xhr = new XMLHttpRequest();

        xhr.open('POST', '/upload/');

        xhr.upload.onprogress = function(e) 
        {
            $('#' + progress).attr('value', e.loaded);
        $('#' + progress).attr('max', e.total);
        };

        xhr.onload = function()
        {
            console.log('upload complete');
        };

        var form = new FormData();
        form.append('title', this.files[i].name);
        form.append('pict', fileInput.files[i]);

        xhr.send(form);

    }

    else
    {
        alert('Your file "' + this.files[i].name + '" \'s format isn\'t supported');    
    }
}

最佳答案

这就是“臭名昭著的循环问题”。

问题出在这里:

xhr.upload.onprogress = function(e) 
{
    $('#' + progress).attr('value', e.loaded);
    $('#' + progress).attr('max', e.total);
};

当此函数运行时,progress 将是循环退出时的状态,而不是循环中定义函数时的状态。尝试用这样的东西替换该代码:

(function(progress) { 
    xhr.upload.onprogress = function(e) 
    {
        $('#' + progress).attr('value', e.loaded);
        $('#' + progress).attr('max', e.total);
    };
}(progress));

更多:Javascript infamous Loop issue?

关于javascript - XHR 带进度条的多文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12712830/

相关文章:

JQuery 文件上传在单独的 Post 请求中发送每个文件?

javascript - Momentjs解析通配符

javascript - React-Native BackHandler 总是在 Android 中关闭 App(硬件回退)

jquery - 获取 Jquery UI 日历以显示在模态弹出窗口顶部

javascript - 根据用户插入的数据属性,从 <ins> 标签中删除选定的文本

java - Spring HTTP 文件上传 : Validation of File Size

android - Android 是否支持 AWS 分段上传?

javascript - 使用Angular的jqlite选择相同类型的元素

javascript - Angular 新手: non-trivial form validation?

JQuery - 在背景位置改变后执行操作