简体   繁体   中英

ReactJS: How to properly link to a download file?

I have a manual.pdf file that I need to attach to my document. The conventional wisdom would be to link the file source in the href attribute of an <a> tag:

<a href="../assets/img/manual.pdf" download>Manual</a>

React seems to not like it, I assume. Failed-No file error is given upon click on the <a> tag.

When it is an <img> tag with a local file, I would import the source import logo from '../assets/img/logo.svg'; , then pass it to the src attribute like so <img src={logo} alt="brand logo" /> .

  • I tried it - no use.
  • giving the absolute path - no use.
  • giving a relative path - no use.

It seems that it does not work the same way with <a> tags. How do I properly link local files in a React Project?

PS I have heard of React routes, but I am not linking to any page, it is for downloading a file.

Try this one https://www.npmjs.com/package/file-saver (FileSaver.js)

//function for saving file
const saveManual = () => {
fileSaver.saveAs(
  process.env.REACT_APP_CLIENT_URL + "../assets/img/manual.pdf",
  "manual.pdf"
);
};

//button for calling 
<button onClick={saveManual}>
    Manual
</button>

Try this

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

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

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