node express content-disposition

bepi_roggiuzza picture bepi_roggiuzza · May 27, 2015 · Viewed 12.6k times · Source

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.

Answer

The Qodesmith picture The Qodesmith · Apr 2, 2016

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