Akhil B
Akhil B

Reputation: 69

How to download a file(.jpg/.txt/.pdf/.mp4) from url in react js?

I am trying to download file from absolute url in react js.

Any help or suggestions are appreciated.

Upvotes: 2

Views: 1721

Answers (3)

NewVigilante
NewVigilante

Reputation: 1319

It would be best if you could create an endpoint which will give you the file with the correct headers. When you create the endpoint, look for Content-Disposition and Content-Type. This will trigger an automatic and consistent download through-out all browsers.

The problem is that front-end code regarding download and the download attribute can behave differently depending on the browser. If you are not able to serve them through an endpoint, I think you will always need to keep the trade-offs in mind like inconsistent behavior through different browsers.

Upvotes: 0

Kundan
Kundan

Reputation: 1952

If you're using React Router, use the below given code.

<Link to="/document/mydocument.pdf" target="_blank" download>Download</Link>

Where /document/mydocument.pdf is inside your public folder.

Upvotes: 1

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

Just do it like this with download attribute.

<a href="path to file" download> Download </a>

Upvotes: 0

Related Questions