javascript 通过使用 Safari 更改 window.location 来下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9723262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:36:40  来源:igfitidea点击:

Download a file by changing window.location w/ Safari

javascripturlsafari

提问by speg

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

我有一个离线 html 文件,它通过将 window.location 设置为生成并保存 CSV

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

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

但是,在 Safari 中,这只会在浏览器中显示 CSV。

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?

强制 Safari 下载文件 - 但它的通用文件名只是“Unknown-3”。有没有办法指定文件名?

回答by josh3736

First, a warning:application/csvisn'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 displaysapplication/octet-stream, which I'd expect to download.)

首先,警告:application/csvis not a valid MIME type,因此在这种情况下它对您“有效”这一事实纯粹是一个实现怪癖,将来很可能会发生变化。(例如,Safari显示application/octet-stream,我希望下载。)

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 blobURI. (Demo)

HTML5 确实有一个<a download="file.name">属性。这会强制浏览器将文件下载到磁盘;它使用属性的值作为默认文件名。它确实与数据 URI 或blobURI结合使用。(演示

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

但是,它目前仅受 Chrome (14+) 支持。Safari 5.1 忽略该属性。



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 filesystemschema:

一种可能的替代方法是使用Filesystem API,但这为您提供了一个沙盒文件夹以供使用。例如,您不能将文件直接保存到用户的 Documents 文件夹中。相反,您可以将文件写入沙箱,然后重定向到新filesystem架构上的文件:

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.

这应该会调用 UA 的下载机制(使用正确的文件名!),但我还没有测试过,因此 Safari 可能只会显示该文件。

回答by antyrat

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

根据RFC 2397没有。没有办法。

Also read thisrelated question.

另请阅读相关问题。