reactjs如何下载文件

2022-01-31 00:00:00 reactjs download javascript

我从 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-TypeContent-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.

相关文章