[英]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.