Javascript 如何从node express服务器下载文件?
我的服务器上有一个文件(Node.js+Express)。我需要将文件从服务器下载到用户的计算机上。 在React应用程序中,我调用将下载文件的函数:Javascript 如何从node express服务器下载文件?,javascript,node.js,reactjs,file,express,Javascript,Node.js,Reactjs,File,Express,我的服务器上有一个文件(Node.js+Express)。我需要将文件从服务器下载到用户的计算机上。 在React应用程序中,我调用将下载文件的函数: downloadFileFromServer(file) { // file -- name of file fetch(`${Config.baseUrl}/download-file/${this.props.params.idEvent}/${file}`, { method: 'GET' }) .then((response)
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文件下载”库
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);
});
});
服务器端的代码如下:
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);
});
});
我对这个答案的参考是在这里
这对我有效。我希望它对您有效。
fetch
不会直接返回数据。您可能需要首先调用response.blob
或response.text
:为什么要将id与req.params.idEvent连接起来?您的参数id是否总是以“id”开头,即id43768926?请尝试以下位置:location.path=${Config.baseUrl}/download file/${this.props.params.idEvent}/${file}
在您的下载逻辑中,该链接丢失了添加的缺少的链接。谢谢,我忘记添加了