简体   繁体   English

如何从 Node 服务器下载 React 中的文件?

[英]How to download files in React from Node server?

My backend: files-routes.js:我的后端:files-routes.js:

router.get('/download/:fid', filesControllers.downloadFile);

filesControllers.js:文件控制器.js:

const downloadFile = async (req, res, next) => {
  const fileId = req.params.fid;
  let filePost;
  try {
    filePost = await File.findById(fileId);
  } catch (err) {
    return next(new HttpError("Error", 500));
  }
  console.log(filePost.file);
  res.download(filePost.file);
}

If I paste in the browser: 'http://localhost:5000/api/files/download/fileId', the file can be downloaded.如果我在浏览器中粘贴:'http://localhost:5000/api/files/download/fileId',则可以下载文件。

My frontend:我的前端:

<Link to={`http://localhost:5000/api/files/download/${props.id}`} target="_blank" download>
  Download File
</Link>

When I click on the link, the file fails to download.当我单击链接时,文件无法下载。 Is there anything I should do?有什么我应该做的吗? I have tried with fetch api try/catch block but still couldn't get it to work.我已经尝试使用 fetch api try/catch 块,但仍然无法让它工作。

Go for simple anchor tags.寻找简单的锚标签。

React-router's Link tags are good if that page lies on one of your routes.如果该页面位于您的一条路线上,则 React-router 的链接标签很好。 Otherwise, just use a simple anchor tags否则,只需使用简单的锚标签

<a href={article.url} target="_blank">
  <img src={article.urlToImage} alt="thumb"/>
</a>

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

相关问题 如何从节点快递服务器下载文件? - How to download files from node express server? 节点FTP从一台服务器下载文件并上传到另一台服务器 - Node FTP download files from one server and upload to another server React 和 Axios 从 Node JS 服务器下载文件 - React and Axios download a file from Node JS server 如何从远程服务器下载一堆文件,并使用Node.js按一定顺序将它们串联起来? - How do I download a bunch of files from a remote server, and concatenate them in a certain order using Node.js? 如何从Node JS服务器下载zip文件夹 - How to download zip folder from node js server 如何将文件从谷歌云存储下载到用户电脑(React) - How to download files from google cloud storage to user pc (React) 我正在尝试将pdf文件从节点服务器下载到React Client,但是当我打开它时,它显示为空白 - I'm trying to download a pdf file from a node server to a react client but when I open it, it shows blank Node.js - 从服务器读取并下载目录中的所有文件并在本地保存 - Node.js - read and download all files in directory from server and save locally 如何在反应中直接在节点响应中下载文件? - How to download file directly in node response in react? 如何在Node.js中一一下载文件? - How to download files one by one in node js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM