Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a file name using window.open

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); 

The file can be successfully downloaded, but how can I name the file data.csv automatically rather than set the name by hand each time?

like image 753
huangcd Avatar asked Aug 12 '11 01:08

huangcd


People also ask

How to set file name JavaScript?

To rename a file we have to create a new file and pass our new name to the File constructor. const myRenamedFile = new File([myFile], 'my-file-final-1-really. txt'); console.

How do I pass a list in Windows Open?

open() method has an explicit parameter for passing in properties like height, width, toolbars, and other properties : window. open(url, target, 'Your Properties Here'); Generally these properties are passed in as a comma delimited list, however if you already have an array with them, you can use the Array.


1 Answers

You can achieve this using the download attribute for <a> elements. For example:

<a href="1251354216241621.txt" download="your-foo.txt">Download Your Foo</a> 

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 the download attribute and .click() it.

var str = "Name, Price\nApple, 2\nOrange, 3"; var uri = 'data:text/csv;charset=utf-8,' + str;  var downloadLink = document.createElement("a"); downloadLink.href = uri; downloadLink.download = "data.csv";  document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); 

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.)

like image 173
Jeremy Avatar answered Oct 01 '22 17:10

Jeremy