node express content-disposition
Asked Answered
A

1

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.

Assured answered 26/5, 2015 at 22:48 Comment(1)
FWIW, your code will do the wrong thing in case the filename contains whitespace, certain delimiters, or non-ASCII characters. See RFC 6266.Lakenyalaker
S
12

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');
});
Slumberland answered 2/4, 2016 at 17:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.