如何在React JS中下载文件 [英] how to download file in react js

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

问题描述

我从api接收文件URL作为响应。当用户单击下载按钮时,应在不打开新选项卡中打开文件预览的情况下下载文件。如何在React JS中实现这一目标?

I receive file url as response from api. when user clicks on download button, the file should be downloaded without opening file preview in a new tab. How to achieve this in react js?

推荐答案

从前端触发浏览器下载是不可靠的。

Triggering browser download from front-end is not reliable.

您应该做的是,创建一个端点,该端点在被调用时将提供正确的响应头,从而触发浏览器下载。

What you should do is, create an endpoint that when called, will provide the correct response headers, thus triggering the browser download.

前端代码只能做很多事情。例如,下载属性可能只是根据浏览器在新选项卡中打开文件。

Front-end code can only do so much. The 'download' attribute for example, might just open the file in a new tab depending on the browser.

您需要查看的响应标题可能是 Content-Type Content-Disposition 。您应该查看此答案以获取更多详细说明。

The response headers you need to look at are probably Content-Type and Content-Disposition. You should check this answer for more detailed explanation.

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

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