huangcd huangcd - 1 year ago 325
Javascript Question

how to set a file name using

I'am trying to download temporary result calculated by javascript. Say I have a string

, I want to download a file contains
and named it as
, I'm using the following code:'data:text/csv;charset=utf-8,' + str);

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

Thank you!

Answer Source

File names can be suggested through HTTP headers, but there's no standard mechanism accomplishing the same thing with data URIs or

There are some ways to specify a filename when downloading generated data, but AFAIK there aren't any that are supported in multiple browsers.

One of these ways is the new 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 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; = "data.csv";


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download