通过使用 Safari 更改 window.location 来下载文件 [英] Download a file by changing window.location w/ Safari

查看:63
本文介绍了通过使用 Safari 更改 window.location 来下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个离线 html 文件,它通过将 window.location 设置为

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

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

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

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

将网址设置为:

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

强制 Safari 下载文件 - 但它获得的通用文件名只是Unknown-3".有没有办法指定文件名?

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?

推荐答案

首先,警告:application/csv 不是 有效的 MIME 类型,因此在这种情况下它对您有效"这一事实纯粹是一个实现怪癖,可以很好地改变将来.(例如,Safari 显示 application/octet-stream,我希望下载.)

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 确实有一个 新的 <一个 download="file.name"> 属性.这会强制浏览器将文件下载到磁盘;它使用属性的值作为默认文件名.它确实可以与数据 URI 或 blob URI.(演示)

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)

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

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

一种可能的替代方法是使用 文件系统 API,但这会给您可以使用沙盒文件夹.您不能—例如—将文件直接保存到用户的 Documents 文件夹中.相反,您可以将文件写入沙箱,然后重定向到新 filesystem 架构上的文件:

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

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

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.

这篇关于通过使用 Safari 更改 window.location 来下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆