假设我在 CDN 上有一个文件(来自 Rackspace 的云文件)和一个带有该文件链接的静态 html 页面。有什么办法可以强制下载这个文件(以防止它在浏览器中打开——例如 mp3)?
我们可以让我们的服务器读取文件并将相应的 header 设置为:
header("Content-Type: application/force-download")
但是我们每个月有大约 500 万次下载,所以我们宁愿让 CDN 来处理。
有什么想法吗?
最佳答案
无法在 HTML 或 JavaScript 中执行此操作。 There is now! (Ish. See @BruceAldrige’s answer below.)
HTTP Content-Disposition
header 告诉浏览器下载文件,这是由服务器发送的。您必须将 CDN 配置为发送该 header 以及您希望浏览器下载而不是显示的任何文件。
不幸的是,我完全不熟悉 Rackspace 的云文件服务,所以我不知道他们是否允许这样做,也不知道如何去做。遗憾的是,刚刚发现 2009 年 12 月的一个页面暗示没有想到:
Cloud Files cannot serve a file with the 'Content-Disposition: attachment' HTTP header. Therefore, a download link that would work perfectly in any other service may result in the browser rendering the file directly. This was confirmed by Rackspace engineers. :-(
我知道您可以使用 Amazon 的 CloudFront 服务,因为它由 S3 提供支持(参见例如 http://blog.cloudberrylab.com/2009/06/how-to-set-custom-http-headers-for.html)
关于javascript - 通过标记或 JS 强制下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2176302/