强制外部下载 url

Force external download url(强制外部下载 url)

本文介绍了强制外部下载 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的网页上托管一个包含 mp3 文件的外部 URL.问题是单击该链接将打开播放器,我必须右键单击并将链接另存为"才能下载文件.有没有办法强制下载文件?

I want to host on my webpage an external url containing a mp3 file. The problem is that clicking on that link will open the player, i have to right click and "Save link as" in order to download the file. Is there any solution to force the file download?

我不想下载文件然后使用标题强制下载.

I don't want to download the file and then use headers to force the download.

推荐答案

现在 HTML5 规范定义超链接上一个非常有用的 download 属性,基本上允许在客户端强制下载行为,而不管 Content-TypeContent-Disposition来自服务器:

Now the HTML5 spec defines a very useful download attribute on hyperlinks that basically allows to force download behavior on client-side, regardless of what comes in Content-Type and Content-Disposition from the server:

在某些情况下,资源旨在供以后使用,而不是立即观看.表示资源旨在download 下载以供以后使用,而不是立即使用属性可以在 aarea 元素上指定hyperlink 到那个资源.

In some cases, resources are intended for later use rather than immediate viewing. To indicate that a resource is intended to be downloaded for use later, rather than immediately used, the download attribute can be specified on the a or area element that creates the hyperlink to that resource.

<...>

download 属性(如果存在)表明作者打算用于下载资源的超链接.该属性可能有价值;该值(如果有)指定默认文件名作者推荐用于标记本地文件中的资源系统.

The download attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource. The attribute may have a value; the value, if any, specifies the default filename that the author recommends for use in labeling the resource in a local file system.

所以你需要做的就是将属性添加到你的超链接中,支持它的浏览器会理解需要下载内容:

So all you need to do is add the attribute to your hyperlink and the browsers that support it would understand that the content needs to be downloaded:

<a href="http://example.com/media.mp3" download>Download Your File</a>

您甚至可以通过设置属性值来为下载的文件建议一个不同的名称:

You can even suggest a different name for the downloaded file by setting the attribute value:

<a href="http://example.com/media.mp3" download="check this out.mp3">Download Your File</a>

更多信息和演示:

  • 在 HTML5 中下载资源:a[下载] (HTML5岩石)
  • HTML5 下载属性 (David Walsh)
  • Downloading resources in HTML5: a[download] (HTML5 Rocks)
  • HTML5 download Attribute (David Walsh)

浏览器支持:caniuse.com

下载生成的内容

您甚至可以创建一个链接来下载您生成的内容,只要有办法为其获取 base64 编码的数据 URI:

You can even make a link that will download a content that you generated, as long as there is a way to get a base64-encoded data URI for it:

<a href="data:application/octet-stream;base64,YOUR_ENCODED_DATA" download="song.mp3">Download</a>

有关保存生成内容的更多详细信息,请参阅 Eli Grey 的这篇文章:

For more details on saving generated content, refer to this article by Eli Grey:

将生成的文件保存在客户端

这篇关于强制外部下载 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:强制外部下载 url

基础教程推荐