如何使用 html 和/或 javascript 强制下载?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8613725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I force download with html and/or javascript?
提问by saoud
So I have a this code:
所以我有一个这样的代码:
<a href="http://mysite.com/song.mp3">My Song</a>
How can I make it so that instead of the user having to right click, save as, they just click the link and BAMit downloads?
我怎样才能做到这一点,而不是用户必须右键单击,另存为,他们只需单击链接并下载它的BAM?
回答by isNaN1247
On the server side, you can send back a Content-Disposition
header, which should work (although its off-spec). See example here:
在服务器端,您可以发回一个Content-Disposition
标头,它应该可以工作(尽管它不符合规格)。请参阅此处的示例:
Uses of content-disposition in an HTTP response header
在 HTTP 响应头中使用 content-disposition
In future you'll be able to benefit from the new download
attribute, part of HTML5.
将来,您将能够从HTML5 的一部分新download
属性中受益。
回答by Purag
The reason this can't be done without a server-side language is the potential security threats that it poses for users.
没有服务器端语言就无法做到这一点的原因是它对用户构成的潜在安全威胁。
You wouldn't like "accidentally" downloading a virus from a site, now would you?
您不希望“意外”从站点下载病毒,是吗?
However, as long as the user's browser doesn't support displaying (or playing, in your case) any filetype, it will automatically prompt the user if they want to download the file. So if a browser doesn't offer support for playing mp3 files (I know Chrome does, maybe Firefox), then it should be "automatically downloaded" when clicked.
但是,只要用户的浏览器不支持显示(或播放,在您的情况下)任何文件类型,它就会自动提示用户是否要下载文件。因此,如果浏览器不支持播放 mp3 文件(我知道 Chrome 支持,也许是 Firefox),那么它应该在点击时“自动下载”。
If you really need another way, though, it can be done with ASP. Hereis a tutorial.
但是,如果您确实需要另一种方式,则可以使用 ASP 来完成。这是一个教程。
回答by MRP
<a type="application/mpeg" href="song.mp3">song link</a>
This will work on every Browser today, except on mobile dispositives. I would like a method with Javascript or simple html to perform this although. I've tried the meta content-disposition and still don't work.
这将适用于今天的所有浏览器,但移动设备除外。不过,我想要一种带有 Javascript 或简单 html 的方法来执行此操作。我已经尝试过元内容配置,但仍然无法正常工作。
回答by Marcela Rocha
Audio files by default gets played by audio player/plug-in.
You should put the files in a ".zip", and write the code to download it:
默认情况下,音频文件由音频播放器/插件播放。
您应该将文件放在“.zip”中,并编写代码来下载它:
<a href="http://mysite.com/song.zip">My Song</a>
That instantly sets the default action to force download.
这会立即设置默认操作以强制下载。