简体   繁体   English

ReactJS:如何正确链接到下载文件?

[英]ReactJS: How to properly link to a download file?

I have a manual.pdf file that I need to attach to my document.我有一个manual.pdf文件,我需要将其附加到我的文档中。 The conventional wisdom would be to link the file source in the href attribute of an <a> tag:传统的智慧是在<a>标签的href属性中链接文件源:

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

React seems to not like it, I assume.我想,React 似乎不喜欢它。 Failed-No file error is given upon click on the <a> tag.失败 -单击<a>标记时未给出文件错误。

When it is an <img> tag with a local file, I would import the source import logo from '../assets/img/logo.svg';当它是带有本地文件的<img>标记时,我会import logo from '../assets/img/logo.svg'; , then pass it to the src attribute like so <img src={logo} alt="brand logo" /> . ,然后将其传递给src属性,如<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.似乎它与<a>标签的工作方式不同。 How do I properly link local files in a React Project?如何在 React 项目中正确链接本地文件?

PS I have heard of React routes, but I am not linking to any page, it is for downloading a file. PS 我听说过 React 路由,但我没有链接到任何页面,它是用于下载文件的。

Try this one https://www.npmjs.com/package/file-saver (FileSaver.js)试试这个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 /files/manual.pdf在您的public

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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