在React组件的锚标签中下载属性 [英] Download attribute in anchor tag in React component

查看:35
本文介绍了在React组件的锚标签中下载属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将文件存储在云中,因此在上传过程中,它们会得到前缀,从而使它们的名称变得唯一.例如,如果我上传一个名为 test.txt 的文件,则在上传过程中该文件将另存为 7ea205f01ae5_test.txt .重要的是要注意,我确实捕获并保存了原始文件名.

I store files in the cloud so during the upload process they get prefixes that make their names unique. For example, if I upload a file named test.txt, during upload it gets saved as 7ea205f01ae5_test.txt. It's important to note that I do capture and save the original file name.

在我的React组件中,我试图通过使用download属性使其对用户友好,以便当用户单击以下载文件时,该文件将以 test.txt 的形式下载,但是它不起作用.该文件仍会下载为 7ea205f01ae5_test.txt .

In my React component, I'm trying to make it user friendly by using the download attribute so that when the user clicks to download the file, it'll be downloaded as test.txt but it's not working. The file still gets downloaded as 7ea205f01ae5_test.txt.

这是我的React代码的样子

This is what my React code looks like

<a href={fileUrl} download={origName}>{fileName}</a>

我的组件看起来像这样的对象:

The object that my component looks like this:

{
  id: 123,
  fileName: "7ea205f01ae5_test.txt",
  origName: "test.txt",
  fileUrl: "https://myBlobStorageUrl.com/container/7ea205f01ae5_test.txt?signature=123abcxyz"
}

请注意,fileUrl包含一个安全访问签名,该签名允许用户访问文件.没有它,用户将无权访问该文件.

Please note that the fileUrl contains a security access signature which allows user to access the file. Without it, user won't be given access to the file.

我需要怎么做才能将文件下载为 test.txt ?

What do I need to do so that the file will be downloaded as test.txt?

推荐答案

正如DroidNoob提到的,这并不是React特有的.任何跨源链接都将使用给定文件名和扩展名的服务器进行下载,但是 download 属性适用于相同的源.

As mentioned by DroidNoob this isn't particular to React. Any cross origin links will download with the server given file name and extension, however the download attribute will work for same origin.

// Domain: example.org

// Downloads as 281c2df7dbce9284dca6059db944f8df.png
<a download="foo.txt" target="_blank" href="https://www.gravatar.com/avatar/281c2df7dbce9284dca6059db944f8df?s=48&d=identicon&r=PG">download</a>

// Downloads as foo.txt
<a download="foo.txt" target="_blank" href="http://example.org/assets/avatar.png">download</a>

根据您的后端,可以设置一条路由,该路由通常将原始名称映射到实际文件名称.因此,前端链接到您的后端映射器,然后依次获取文件.

Depending on your backend, you could possible set up a route that generically maps the original names to the actual files names. So the frontend links to your backend mapper, and it in turns grabs the file.

这篇关于在React组件的锚标签中下载属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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