简体   繁体   中英

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

you can do it by this way

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

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>

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM