0

how can i send a file(docx) to a user ? this is my server code :

  app.get('/api/topic/file/:id', function (req, res, next) {
    Topic.findByIdAndUpdate(req.params.id)
      .exec()
      .then((topic) => {
        let filepath = topic.news_file[0]
        console.log('filepath', filepath)
        res.download(filepath, topic.name + '.docx', function (err) {
          if (err) {
            console.log('api get file err ', err);
          } else {
            // decrement a download credit, etc.
          }
        });
      }).catch((err) => console.log('error', err));
  })

this does not trigger a download on the browser. i am using react as front-end. on the client i have a button triggering this upon click :

handleDownload() {
        if (this.state.lastClicked) {
          fetch("/api/topic/file/" + this.state.lastClicked._id)
            .then(results => {
              console.log('results', results)
              return results;
            })
        } else {
            //somthings...
        }
      }
Almog Hazan
  • 147
  • 1
  • 2
  • 7

1 Answers1

2

Found a solution using downloadjs..

var download = require("downloadjs")
 async handleDownload() {
    const res = await fetch("/api/topic/file/" + this.state.lastClicked._id);
    const blob = res.blob();
    download(blob, this.state.lastClicked.name + '.docx');
  }
Almog Hazan
  • 147
  • 1
  • 2
  • 7