Javascript 仅上载大文件(100mb+;)时崩溃
我允许用户通过网站上传CSV文件。使用JavaScript文件API读取文件,然后将其发送到要保存的服务器Javascript 仅上载大文件(100mb+;)时崩溃,javascript,ajax,backbone.js,uploading,jqxhr,Javascript,Ajax,Backbone.js,Uploading,Jqxhr,我允许用户通过网站上传CSV文件。使用JavaScript文件API读取文件,然后将其发送到要保存的服务器 , upload: function (prefix, numberType, file, name) { this.attributes = { // Set the data to be sent along 'upload': true, 'prefix': prefix, 'file': file, 'na
, 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在处理大文件时遇到的已知问题吗
我认为真正解决这个问题的唯一方法是将文件分割成块,然后在服务器上重新组合起来。这当然是可能的,但值得一提的是,这是否是将来需要注意的限制。浏览器崩溃是因为内存不足 不要在内存中加载文件,而是将file对象传递给XMLHttpRequest,这样Chrome就可以以上传形式传输文件内容 为此使用
FormData
对象:
//您的文件输入
const file=document.getElementById('file').files[0];
//你的表格
var form=new FormData();
form.append('file',file);
const xhr=$.ajaxSettings.xhr();
xhr.upload.onprogress=函数(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
发送(表格)代码>