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 is it possible only with HTML/JavaScript?
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.
you can use the download attribute
<a href="http..." download></a>
or specify a filename using
<a href="http..." download="filename.pdf"></a>
see more: https://developer.mozilla.org/en/HTML/element/a#attr-download
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.