HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptreactMajor

how to download file in react js

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
downloadreacthowfile

Problem

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?

Solution

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.

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.

Context

Stack Overflow Q#50694881, score: 83

Revisions (0)

No revisions yet.