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

查看:117
本文介绍了如何强制下载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?

推荐答案

自动将取决于浏览器及其选项。但是您可以通过发生什么(然后再与用户进行双重检查) rfc2183.txtrel =nofollow noreferrer> 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匹配的规则,并使用 标题指令

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天全站免登陆