如何使用 HTML/JavaScript 强制下载? [英] How do I force download with HTML/JavaScript?

查看:25
本文介绍了如何使用 HTML/JavaScript 强制下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个链接,如果用户点击它,我需要发生两件事:

I have a link and, if a user clicks it, I need 2 things to happen:

  • 向用户发送正确的 HTTP 响应(尤其是使用 Content-Type: video/mp4)
  • 视频文件将自动开始下载.

我在 PHP 中看到过类似的东西,但是否只能使用 HTML/JavaScript?

I have seen something of the sort with PHP, but is it possible only with HTML/JavaScript?

推荐答案

自动 很大程度上取决于浏览器及其选项.但是您可以通过 Content-Disposition 响应中的标头.例如,将其设置为 attachment;filename=blah.mp4 将在大多数浏览器上邀请用户下载它(使用该文件名),即使浏览器通常会尝试显示/播放内容在其自己的界面中.有关详细信息,请参阅链接.(下载可能是 mp4 文件的默认设置,但这取决于用户;我发现这在为 HTML 文件提供下载链接时很有帮助.)

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.)

如果您不使用服务器端脚本(正如您所说的那样),您可以通过 Web 服务器中的配置来设置标头.例如,对于 Apache,您将使用与这些视频文件的 URL 匹配的规则,并使用 Header 指令.

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.

这篇关于如何使用 HTML/JavaScript 强制下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆