Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot specify name of the download file using Javascript

I am using Javascript to create a CSV file for user to download.

Until May 22nd, Chrome still downloaded the file with the name I specified. However, today I found that the files downloaded are named "download" and do not have the extension .csv.

This problem does not exist in Firefox!

Here is a fiddle with sample Javascript:

var A = [['n','sqrt(n)']];  // initialize array of rows with header row as 1st item
for(var j=1;j<10;++j){ A.push([j, Math.sqrt(j)]) }
var csvRows = [];
for(var i=0,l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));   // unquoted CSV row
}
var csvString = csvRows.join("\n");

var a = document.createElement('a');
a.href     = 'data:text/csv;charset=utf-8;base64,' + window.btoa(csvString);
a.target   = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
like image 544
Koshien Avatar asked May 25 '14 21:05

Koshien


People also ask

How do I trigger a download when clicking HTML button or JavaScript?

To trigger a file download on a button click we will use a custom function or HTML 5 download attribute. The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded.


1 Answers

Nice work! This is a regression.

I just created another fiddle, and filed a Chrome bug.

If you're interested, star it in the bug tracker.

<a href="/" download="my-downloaded-file.html" target="_blank">Click here</a>

EDIT: It look like it depends on the URL. Absolute URLs work, as well as objects URLs (according to https://code.google.com/p/chromium/issues/detail?id=376197).

like image 54
Paul Draper Avatar answered Sep 30 '22 18:09

Paul Draper