Download a file by changing [removed] w/ Safari

2019-02-14 04:35发布

问题:

I have an offline html file that generates and saves a CSV by setting window.location to

data:text/csv;base64,Intfa2V5fSIsInt...

However, in Safari this just brings up the CSV in the browser.

Setting the url to:

data:application/csv;base64,Intfa2V5fSIsInt...

forces Safari to download the file - but it gets a generic file name of just 'Unknown-3'. Is there a way to specify the file name?

回答1:

First, a warning:application/csv isn't a valid MIME type, so the fact that it "works" for you in this case is purely an implementation quirk that could very well change in the future. (For example, Safari displays application/octet-stream, which I'd expect to download.)

HTML5 does have a new <a download="file.name"> attribute. This forces the browser to download the file to disk; it uses the attribute's value as the default file name. It does work in conjunction with a data URI or a blob URI. (Demo)

However, it is currently only supported by Chrome (14+). Safari 5.1 ignores the attribute.


A possible alternative is to use the Filesystem API, but that gives you a sandboxed folder to work with. You can't—for example—save a file directly to the user's Documents folder. Instead, you can write a file to the sandbox and then redirect to file on the new filesystem schema:

location.assign('filesystem:http://example.com/temporary/somefile.csv');

This should invoke the UA's download mechanism (with the right filename!), but I haven't tested this, so it is possible Safari will just display the file anyway.



回答2:

According to the RFC 2397 no. There is no way.

Also read this related question.