如何使用 HTML/JavaScript 强制下载?
我有一个链接,如果用户单击它,我需要发生两件事:
- 向用户发送正确的 HTTP 响应(尤其是
Content-Type: video/mp4
) - 和视频文件将自动开始下载。
我在 PHP 中见过类似的东西,但是只有 HTML/JavaScript 才可能吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用下载属性
或使用查看更多指定文件名
: https:// /developer.mozilla.org/en/HTML/element/a#attr-download
you can use the download attribute
or specify a filename using
see more: https://developer.mozilla.org/en/HTML/element/a#attr-download
自动很大程度上取决于浏览器及其选项。但是您可以通过
Content-Disposition
响应中的标头。例如,将其设置为attachment;filename=blah.mp4
在大多数浏览器上,将邀请用户下载它(使用该文件名),即使浏览器通常会尝试显示/播放其自己的界面中的内容。详细信息请参阅链接。 (下载可能是 mp4 文件的默认设置,但这取决于用户;我发现这在提供 HTML 文件的下载链接时很有帮助。)如果您不使用服务器端,则可以通过 Web 服务器中的配置设置标头脚本(正如你所说,你不是)。例如,使用 Apache,您可以使用与这些视频文件的 URL 匹配的规则,并使用
标头
指令。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 toattachment;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.不,这是不可能的(至少对于仅限于客户端 JavaScript 的 JavaScript 值而言)。
如果要覆盖浏览器处理 HTTP 资源的默认行为,则需要使用 HTTP 标头来实现。如果您想正确执行此操作,请使用内容处置标头(带有附件价值)。
您可以使用 服务器端 JavaScript 或(几乎)任何其他服务器设置此标头侧面环境。
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.
我 找到了使用库Axios强制下载的可靠方法
I found a reliable way of forcing a download using the library Axios