具有下载属性的锚标记将打开文件,而不是下载文件 [英] Anchor tag with download attribute opens file instead of downloading

查看:63
本文介绍了具有下载属性的锚标记将打开文件,而不是下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Reactjs应用程序中,我使用了定位标记来下载一个txt文件,如下所示.

In my Reactjs application I used the anchor tag to download a txt file like below.

<a href="http://textfiles.com/......./sample.txt" download>download</a>

我在其中添加了 download 属性,以强制其下载而不是在浏览器标签中将其打开.

There I added download attribute to force it to download instead open it in the browser tab.

但是它仍在同一选项卡中打开而不是下载.谁能帮我解决这个问题.

But it is still opening in the same tab instead of downloading. Can any one help me to solve this problem.

推荐答案

以您的示例为例,您似乎使用的不是同一来源,这可能会导致问题.

Looking at your example seems you're not using same origin and that might have cause the problem.

如果您要下载存在于同一来源的文件,那么我建议您使用相对URL而不是绝对URL.

If you're trying to download the file which exists in same origin then I suggest you to use relative url rather than absolute url.

示例:

<a href="/public/sample.txt" download>download</a>

请查看 docs :

属性:下载

注释:

  • 此属性仅适用于相同来源的网址.
  • 尽管HTTP URL必须使用相同的来源,但数据:URL ,以便由JavaScript生成的内容, 这样的 作为在图像编辑器Web应用程序中创建的图片,可以下载.
  • 如果HTTP标头 Content-Disposition :提供了不同的文件名 比此属性,HTTP标头对此具有更高的优先级 属性.
  • 如果将Content-Disposition:设置为内联,则Firefox会优先处理 Chrome优先处理内容配置,例如文件名大小写 下载属性.
  • This attribute only works for same-origin URLs.
  • Although HTTP(s) URLs need to be in the same-origin, blob: URLs and data: URLs are allowed so that content generated by JavaScript, such as pictures created in an image-editor Web app, can be downloaded.
  • If the HTTP header Content-Disposition: gives a different filename than this attribute, the HTTP header takes priority over this attribute.
  • If Content-Disposition: is set to inline, Firefox prioritizes Content-Disposition, like the filename case, while Chrome prioritizes the download attribute.

这篇关于具有下载属性的锚标记将打开文件,而不是下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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