0

I'm trying to trigger a file download when a POST request is sent to my server. Here is what I tried:

router.post('/generate', function (req, res) {
  console.log('THIS IS RUNNING');
  var file = __dirname + '/blah.txt';
  res.download(file);
});

However, the res.download(file); doesn't seem to be doing anything. When the browser sends a /generate POST request, nothing gets downloaded. I know for sure that the function is running because the console is logging that message.

Any help would be appreciated!

Saad
  • 49,729
  • 21
  • 73
  • 112
  • I could be wrong, but try removing the slash? As in `var file = __dirname + 'blah.txt';` – MPawlak Sep 25 '16 at 22:14
  • [Possible duplicate](http://stackoverflow.com/questions/7288814/download-a-file-from-nodejs-server-using-express) – Jairo Malanay Sep 26 '16 at 06:30
  • Are you requesting `/generate` using XHR ("AJAX")? If so: you can't trigger regular file downloads using XHR. A possible solution can be found [here](http://stackoverflow.com/a/16323408/893780). – robertklep Sep 26 '16 at 06:53

1 Answers1

-1

Use '//' as single slash ignore the letters.

router.post('/generate', function (req, res) {
  console.log('THIS IS RUNNING');
  var file = __dirname + '//blah.txt';
  res.end(file);
});

For download popup first create this API as GET and then set Content-Disposition as below:

router.get('/generate',function (req, res) {
  res.set('Content-Disposition', 'attachment; filename=this.txt')
  res.download(__dirname + '\\this.txt')
});
Sachin
  • 2,912
  • 16
  • 25