How to download files from node express server?

只愿长相守 提交于 2021-02-11 15:23:40

问题


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?


回答1:


you have to install "js-file-download" library in react using following command

npm install --save js-file-download

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);
     });
}

the code at server side is as follows:

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.



来源:https://stackoverflow.com/questions/55171911/how-to-download-files-from-node-express-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!