Javascript:导出大文本/csv 文件会导致 Google Chrome 崩溃
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23301467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: Exporting large text/csv file crashes Google Chrome
提问by Ben Wong
I have the following Javascript code to export CSV file on the client side. However Google Chrome crashes every time I try to export a large array. What is the limit of the data string allowed in Chrome? Is it possible that it is hitting the memory limit allowed in Chrome? If the data string is too long for Chrome, how will I go about exporting large CSV files on the client side?
我有以下 Javascript 代码可以在客户端导出 CSV 文件。但是,每次我尝试导出大型数组时,Google Chrome 都会崩溃。Chrome 中允许的数据字符串的限制是多少?是否有可能达到 Chrome 中允许的内存限制?如果 Chrome 的数据字符串太长,我将如何在客户端导出大型 CSV 文件?
var csvRows = [...]; //Array with 40000 items, each item is 100 characters long.
var csvString = csvRows.join("\r\n");
var a = document.createElement('a');
a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvString);
a.target = '_blank';
a.download = 'export.csv';
document.body.appendChild(a);
a.click();
(Expected file size is about 6.4MB)
(预计文件大小约为 6.4MB)
回答by jan
had the same Problem and solved it using Blob.
有同样的问题并使用Blob解决了它。
For example:
例如:
csvData = new Blob([csvString], { type: 'text/csv' });
var csvUrl = URL.createObjectURL(csvData);
a.href = csvUrl;
回答by Ganesh
I used following function to download CSV. Worked for me in IE/Firefox/Chrome
我使用以下功能下载 CSV。在 IE/Firefox/Chrome 中对我来说有效
function downloadFile(data, fileName) {
var csvData = data;
var blob = new Blob([ csvData ], {
type : "application/csv;charset=utf-8;"
});
if (window.navigator.msSaveBlob) {
// FOR IE BROWSER
navigator.msSaveBlob(blob, fileName);
} else {
// FOR OTHER BROWSERS
var link = document.createElement("a");
var csvUrl = URL.createObjectURL(blob);
link.href = csvUrl;
link.style = "visibility:hidden";
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}