10

I want to force the browser to download a file from an external storage, given an url. I implemented this express controller post action:

var download = function(req, res) {
    request(req.body.url).on('response', function(response) {
        res.set({
            'Content-Disposition': 'attachment; filename=' + req.body.filename,
            'Content-Type': response.headers['content-type']
        });
    })
    .pipe(res);
};

I don't know why the browser always receive a "inline" instead of "attachment", avoiding me to download the file.

In this case I use express and request, the server is hosted on Heroku and the server that hosts files is FilePicker.

bepi_roggiuzza
  • 195
  • 1
  • 3
  • 12
  • 2
    FWIW, your code will do the wrong thing in case the filename contains whitespace, certain delimiters, or non-ASCII characters. See RFC 6266. – Julian Reschke Jan 16 '18 at 17:14

1 Answers1

11

I'm searching around for the very same thing. Express' documentation shows a very simple helper method right out of the box:

var express = require('express');
var app = express();

app.get('/download', function(req, res) {
  res.download('/path/to/your_file.pdf');
});
Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
The Qodesmith
  • 3,205
  • 4
  • 32
  • 45