How do I force download with HTML/JavaScript?

后端 未结 3 764
长发绾君心
长发绾君心 2020-11-30 10:41

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
相关标签:
3条回答
  • 2020-11-30 11:03

    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

    0 讨论(0)
  • 2020-11-30 11:13

    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.

    0 讨论(0)
  • 2020-11-30 11:27

    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.

    0 讨论(0)
提交回复
热议问题