Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Exporting large text/csv file crashes Google Chrome

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?

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)

like image 398
Ben Wong Avatar asked Apr 25 '14 19:04

Ben Wong


2 Answers

had the same Problem and solved it using Blob.

For example:

csvData = new Blob([csvString], { type: 'text/csv' }); 
var csvUrl = URL.createObjectURL(csvData);
a.href =  csvUrl;

Source: https://stackoverflow.com/a/24611096/3048937

like image 50
jan Avatar answered Oct 27 '22 16:10

jan


I used following function to download CSV. Worked for me in 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);
        }
}
like image 13
Ganesh Avatar answered Oct 27 '22 17:10

Ganesh