I'am trying to download temporary result calculated by javascript. Say I have a string str
, I want to download a file contains str
and named it as data.csv
, I'm using the following code:
window.open('data:text/csv;charset=utf-8,' + str);
OK, the file can be successfully downloaded, but how can I name the file data.csv
automatically rather than set the name each time by hand?
Thank you!
A solution for IE is to use msSaveBlob and pass the file name.
For modern browsers solution goes like this, tested: IE11, FF & Chrome
There is a good discution about that here
That does not work in latest Chrome, I have modified that and the following code will work fine,
So when you click on download_1 id button then it will create an invisible download link and click that. I have used another function to prepare js.
The JSON2CSV function is as follows:
Hope it will help others :)
A shorter version of accepted one (for my case had to use unicode)
You can achieve this using the
download
attribute for<a>
elements. For example:This attribute indicates that the file should be downloaded (instead of displayed, if applicable) and specifies which filename should be used for the downloaded file.
Instead of using
window.open()
you could generate an invisible link with thedownload
attribute and.click()
it.Unfortunately this isn't supported in all browsers, but adding it won't make things worse for other browsers: they'll continue to download the files with useless filenames. (This assumes that you're using a MIME type is that their browser attempts to download. If you're trying to let the user download an
.html
file instead of displaying it, this won't do you any good in unsupported browsers.)