node.jsreactjsmongodbaxiosgridfs

File download from mongodb atlas to client(react js) using node js


I am a beginner in Reactjs and Nodejs. I am trying to download a file(.pdf,.jpg) from mongodb atlas in react using node js. I have used createReadStream method from Gridfs to fetch the data at server, need to send this data as a file to react so that user can download it when required. But can't get the file at client side.

FileServer.js

app.use('/download', (req, res) => {
  // Check file exist on MongoDB
var filename = req.query.filename;
console.log(req.body.filename);

gfs.exist({ filename: req.body.filename ,"root": "uploads"}, (err, file) => {
    console.log(file);
      if (err || !file) {
        console.log("error")
          res.status(404).send('File Not Found');
          return
      } 

      res.setHeader('Content-Type', 'application/octet-stream');
      res.setHeader('Content-Disposition', 'attachment; filename="'+req.body.filename+'"');
var str='';
var readstream = gfs.createReadStream({ filename: req.body.filename });  
readstream.pipe(res);    

  });
});  

FileClient.js

onSubmitDownload(e){
        e.preventDefault();
    axios.post("http://localhost:3000/file_server/download", {filename:'MyFile.pdf'})
    .then(res => res.data).then(res=>this.setState({
        msg:res
    }));
}

Unable to take response in file format


Solution

  • The trick was in getting the response in the format we want, here we need to receive the data in file format. So the code at client side using Filesaver is

    onSubmitDownload(e){
      e.preventDefault();
      axios({
        method: "GET",
        url: "http://localhost:8000/download",
        responseType: "blob",
      })
        .then((response) => {
          this.setState({ fileDownloading: true }, () => {
            FileSaver.saveAs(response.data, data1);
            console.log(response);
          });
        })
        .then(() => {
          this.setState({ fileDownloading: false });
          console.log("Completed");
        });
    }
    

    you can also check https://github.com/ANS-Developers113/File-Upload-Download-Application