如何从节点快递服务器下载文件? [英] How to download files from node express server?
问题描述
我的服务器上有一个文件(Node.js + Express).我需要将文件从服务器下载到用户的计算机.在React应用程序中,我调用了将下载文件的函数:
I have a file on my server (Node.js + Express). I need to download file from server to computer of user. in React app I call the function which would download file:
downloadFileFromServer(file) { // file -- name of file
fetch(`${Config.baseUrl}/download-file/${this.props.params.idEvent}/${file}`, {
method: 'GET'
})
.then((response) => {
if (response.status >= 400) {
throw new Error('Bad response from server');
}
return response;
});
}
在后端,我有这条路线:
On backend I have this route:
app.route('/download-file/:idEvent/:fileName')
.get((req, res) => {
const id = `id${req.params.idEvent}`;
const dir = `${Config.basePath}/${id}/${req.params.fileName}`;
res.download(dir); // dir -- path to server's files. (something like this: 'var/www/... path to directory ...')
});
结果我没有任何结果.什么都没发生,控制台(前端,后端)为空,没有错误.
In result I haven't any results. Nothing happend, consoles (frontend, backend) are empty, without errors.
为什么我不能下载文件?如何解决?
Why I can't download file? How to fix it?
推荐答案
您必须使用以下命令在React中安装"js-file-download"库
you have to install "js-file-download" library in react using following command
npm install --save js-file-download
然后在react文件中添加如下代码:
then the code in react file as follows:
import download from 'js-file-download';
downloadFile = () => {
axios.get("localhost:3030/getfile")
.then(resp => {
download(resp.data, fileName);
});
}
服务器端的代码如下:
router.get("/getfile", (req, res) => {
FileLocation ="public/FILE.pdf"
file="File.pdf"
res.download(fileLocation, file, (err) => {
if (err) console.log(err);
});
});
我对这个答案的参考是在这个链接中.
My reference for this answer is in this link.
这对我有用.希望它对您有用.
This works for me.I hope it works for you.
这篇关于如何从节点快递服务器下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!