views:

73

answers:

2

Hi guys,

I have a link and if a user clicks it I need 2 things to happen: A proper HTTP response is sent to the user (especially with Content-Type: video/mp4) and a video file will automatically begin downloading. I have seen something of the sort with php, but I need it only with html/javascript. Is this possible?

Thanks

Alex

+1  A: 

No, this is not possible (at least for values of JavaScript limited to client-side JavaScript).

If you want to override the default behavior of how a browser handles an HTTP resource, you need to do it with HTTP headers. If you want to do it correctly, use the content-disposition header (with an attachment value).

You can set this header using server-side JavaScript or (pretty much) any other server side environment.

David Dorward
A: 

Automatically will depend a lot on the browser and its options. But you can tell the browser what you want to have happen (which it will then double-check with the user) via the Content-Disposition header in the response. For instance, setting it to attachment;filename=blah.mp4 will, on most browsers, invite the user to download it (using that filename) even if normally the browser would have tried to display/play the content in its own interface. See the link for details. (Downloading is probably the default for mp4 files, but that's up to the user; I find this helpful when offering download links for HTML files.)

You can set the header via configuration in your web server if you're not using server-side scripting (as you've said you're not). For instance, with Apache you'd use a rule matching the URL for these video files and use the Header directive.

T.J. Crowder
(This is -- or at least, *was* -- not a duplicate answer. [I hate duplicate answers.] David edited his answer to include `Content-Disposition` *after* I posted mine about it.)
T.J. Crowder
And this answer wasn't there when I started editing :)
David Dorward
@David: I should have been clear that I wasn't criticizing. It's perfectly acceptable to improve one's answer. Just noting lest duplicate-answer fascists come after me. :-)
T.J. Crowder