javascriptreactjsdownload

how to download file in 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?


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.