how to download file in react js(reactjs如何下载文件)
问题描述
我从 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 the frontend is not reliable.
你应该做的是,在服务器上创建一个端点,当被调用时,它会以正确的响应头响应,从而触发浏览器下载.
What you should do is, create an endpoint on a server that when called, responds with the correct response headers, thus triggering the browser download.
前端代码只能做这么多.例如,下载"属性可能只是在新选项卡中打开文件,具体取决于浏览器和文件类型.
Frontend code can only do so much. The 'download' attribute for example, might just open the file in a new tab depending on the browser and the type of the file.
您需要查看的响应标头是 Content-Type
和 Content-Disposition
.您应该查看此答案以获取有关这些标题的更详细说明.
The response headers you need to look at are Content-Type
and Content-Disposition
. You should check this answer for a more detailed explanation on those headers.
这篇关于reactjs如何下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:reactjs如何下载文件


- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01