Daniel Isaac Chavez
Daniel Isaac Chavez

Reputation: 101

button to download a file in reactJS

I am currently working on a personal portfolio, I am trying to make a button that if you click it should download a Resume.

code

<form method="get" action="fileName">
        <button class="myButton" type="submit">Download!</button>
</form>

let the user download the file.

I am working in REACTJS, create-react-app

Upvotes: 4

Views: 30287

Answers (4)

Dani_justme
Dani_justme

Reputation: 11

import MyPDF from '../path/to/file.pdf';    
<a href={myPDF} download="My_File.pdf"> Download Here </a>    

Replace with your stuff

Upvotes: 0

Nemer
Nemer

Reputation: 687

you can do it by this way

<a href="./yourfile.pdf" download>Download CV</a>

Upvotes: 4

alshafi
alshafi

Reputation: 1219

You can use FileSaver.js to achieve this goal:

Install the npm package: npm install file-saver --save

const saveFile = () => {
fileSaver.saveAs(
  process.env.REACT_APP_CLIENT_URL + "/resources/cv.pdf",
  "MyCV.pdf"
);

};

<button className="cv" onClick={saveFile}>
    Download File
</button>

Upvotes: 4

Rohan Kumar
Rohan Kumar

Reputation: 862

I have the exact same problem, and here is the solution I make use of now:

Steps

3 steps:

  1. Make use of file saver in project: npmjs/package/file-saver (npm install file-saver or something)
  2. Place the file in your project You say it's in the components folder. Well, chances are if you've got web-pack it's going to try and minify it.(someone please pinpoint what webpack would do with an asset file in components folder), and so I don't think it's what you'd want. So, I suggest to place the asset into the public folder, under a resource or an asset name. Webpack doesn't touch the public folder and index.html and your resources get copied over in production build as is, where you may refer them as shown in next step.
  3. Refer to the file in your project Sample code:
    import FileSaver from 'file-saver';
    FileSaver.saveAs(
        process.env.PUBLIC_URL + "/resource/file.anyType",
        "fileNameYouWishCustomerToDownLoadAs.anyType");
    

Source

Appendix

Not useful, still good answers here:

Upvotes: 2

Related Questions