Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 942
Sameer Thite Avatar asked Jun 05 '18 07:06

Sameer Thite


People also ask

How do you download a file with react?

To Download File in React js It is simple to download file in React app just use the anchor tag in your react app just like this: <a href='../path/to/file. txt' download>Click Here to download</a> And this is how you can download file in react js app.


2 Answers

This is not related to React. However, you can use the download attribute on the anchor <a> element to tell the browser to download the file.

<a href='/somefile.txt' download>Click to download</a> 

This is not supported on all browsers: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a

like image 161
lipp Avatar answered Oct 20 '22 16:10

lipp


If you are using React Router, use this:

<Link to="/files/myfile.pdf" target="_blank" download>Download</Link> 

Where /files/myfile.pdf is inside your public folder.

like image 21
Javier López Avatar answered Oct 20 '22 14:10

Javier López