【问题标题】:Uploading large file (100mb+) crashes Chrome only上传大文件 (100mb+) 只会使 Chrome 崩溃
【发布时间】:2019-04-23 20:17:35
【问题描述】:

我允许用户通过网站上传 CSV 文件。使用 JavaScript 文件 API 读取文件,然后将其发送到服务器进行保存。

,   upload: function (prefix, numberType, file, name)
{
    this.attributes = { // Set the data to be sent along
        'upload': true,
        'prefix': prefix,
        'file': file,
        'name': name,
        'numberType': numberType 
    };

    console.log('upload', this) // This will correctly show in the console

    return this.sync('create', this, { // This is when Chrome crashes
        xhr: function() {
            var xhr = $.ajaxSettings.xhr();
            xhr.upload.onprogress = function(evt){
                document.querySelector('.uploadProgressBar').style.width = parseInt(evt.loaded/evt.total*100) + '%';
                document.querySelector('#uploadNow').classList.add('percentageUpload');
                document.querySelector('#uploadNow').innerText = parseInt(evt.loaded/evt.total*100) + '%';
            };
            return xhr;
        }
    });
}

在检查网络选项卡时,似乎从未发送过请求,因此在创建请求时它会中断。这只会在文件大约 100mb 并且较小的文件可以正常上传时中断。除此之外,它在 Safari 和 Firefox 上都可以正常工作,因此这是 Chrome 的特定问题。这是 Chrome 处理大文件时遇到的已知问题吗?

我认为真正解决此问题的唯一方法是将文件拆分为多个块,然后在服务器上将其重新组合在一起。这当然是可能的,但值得了解它是否是未来需要注意的限制。

【问题讨论】:

    标签: javascript ajax backbone.js uploading jqxhr


    【解决方案1】:

    浏览器因内存不足而崩溃。

    不是将文件加载到内存中,而是将文件对象传递给 XMLHttpRequest,以便 Chrome 可以在上传表单中流式传输文件内容。

    为此使用FormData 对象:

    // your file input
    const file = document.getElementById('file').files[0];
    // your form
    var form = new FormData();
    form.append('file', file);
    
    const xhr = $.ajaxSettings.xhr();
    
    xhr.upload.onprogress = function(evt) {
      document.querySelector('.uploadProgressBar').style.width = parseInt(evt.loaded / evt.total * 100) + '%';
      document.querySelector('#uploadNow').classList.add('percentageUpload');
      document.querySelector('#uploadNow').innerText = parseInt(evt.loaded / evt.total * 100) + '%';
    };
    xhr.open('POST', 'http://example.com/'); // Url where you want to upload
    xhr.send(form);

    【讨论】:

      猜你喜欢
      • 2020-06-05
      • 1970-01-01
      • 2014-06-11
      • 2014-09-18
      • 2019-10-18
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 2021-07-30
      相关资源
      最近更新 更多