开发者

Force download through markup or JS

Lets assume I have a file on a CDN (Cloud Files from Rackspace) and a static html page with a link to that file. Is there any way I can force download this file (to prevent it from opening in the browser -- for mp3s for example)?

We could make our server r开发者_运维问答ead the file and set the corresponding header to:

header("Content-Type: application/force-download")

but we have about 5 million downloads per month so we would rather let the CDN take care of that.

Any ideas?


There’s no way to do this in HTML or JavaScript. There is now! (Ish. See @BruceAldrige’s answer below.)

The HTTP Content-Disposition header is what tells browsers to download the files, and that’s sent by the server. You have to configure the CDN to send that header with whichever files you want to browser to download instead of display.

Unhelpfully, I’m entirely unfamiliar with Rackspace’s Cloud Files service, so I don’t know if they allow this, nor how to do it. Just found a page from December 2009 that suggests not thought, sadly:

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. :-(

http://drupal.org/node/656714

I know that you can with Amazon’s CloudFront service, as it’s backed by S3 (see e.g. http://blog.cloudberrylab.com/2009/06/how-to-set-custom-http-headers-for.html)


You can use the download attribute:

<a href="http..." download></a>

https://stackoverflow.com/a/11024735/21460

However, it’s not currently supported by Safari (7) or IE (11).


Yes, you can do this through the cloudfiles API. Using the method stream allows you to stream the contents of files in - setting your own headers etc.


A crazy idea: download via XMLHttpRequest and serve a data: URL with the content type you want? :P

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜