我在服务器上有一个文件(node.js express)。我需要将文件从服务器下载到用户计算机。在React App中,我调用将下载文件的函数:
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;
});
}
在后端我有这条路线:
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 ...')
});
结果我没有任何结果。没有任何事情发生,控制台(前端,后端)是空的,没有错误。
为什么我不能下载文件?如何修复它?
您必须在React中使用以下命令
安装" JS-File-Doalload"库npm install --save js-file-download
然后在React文件中的代码如下:
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);
});
});
我对此答案的参考是在此链接中。
这对我有用。我希望它对您有用。