代码之家  ›  专栏  ›  技术社区  ›  AnthonyG95

上载大文件(100MB以上)只会导致Chrome崩溃

  •  1
  • AnthonyG95  · 技术社区  · 7 年前

    我允许用户通过网站上传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是否存在已知问题?

    我在想真正解决这个问题的唯一方法是将文件分割成块,然后在服务器上重新拼合。这当然是有可能的,但有必要弄清楚这是否是将来需要注意的限制。

    1 回复  |  直到 7 年前
        1
  •  1
  •   rubentd    7 年前

    由于内存不足,浏览器崩溃。

    不是在内存中加载文件,而是将文件对象传递给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);