上传大文件(100mb+)只会导致Chrome崩溃



我允许用户通过网站上传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在处理大文件时遇到的已知问题吗?

我认为真正解决这个问题的唯一方法是将文件分割成块,然后在服务器上重新拼凑起来。这当然是可能的,但如果这是未来需要注意的限制,那就值得一探究竟了。

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

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

最新更新