4

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

4 Answers4

4

you can do it by this way

<a href="./yourfile.pdf" download>Download CV</a>
Nemer
  • 667
  • 1
  • 6
  • 10
  • 3
    Actually it does the download but it says the Failed - No file. – Daniel Isaac Chavez Jul 17 '19 at 20:53
  • 1
    you have to give the right path: for example if your file in public folder "/filePath.pdf" – Nemer Jul 17 '19 at 21:15
  • it is in my components folder which my main.js file is too. so what I have is "./document.pdf" – Daniel Isaac Chavez Jul 17 '19 at 21:39
  • 1
    try to move the file to public folder and the path will be "/document.pdf" – Nemer Jul 17 '19 at 21:44
  • @DanielIsaacChavez if it is downloading, but shows an error like "Failed to load PDF document" when trying to open the pdf, it may be that you are using a *relative* path on your href and the final path it generates does not match the one were you have stored your file. Try using an absolute path on href. It should start with a slash / – spuente Sep 05 '22 at 19:08
4

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>
alshafi
  • 969
  • 7
  • 8
2

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:

Rohan Kumar
  • 726
  • 10
  • 17
0
import MyPDF from '../path/to/file.pdf';    
<a href={myPDF} download="My_File.pdf"> Download Here </a>    

Replace with your stuff