Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node express content-disposition

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.

like image 495
bepi_roggiuzza Avatar asked May 26 '15 22:05

bepi_roggiuzza


People also ask

What is content-disposition in js?

In a regular HTTP response, the Content-Disposition response header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally.

What does res sendFile do?

The res. sendFile() function basically transfers the file at the given path and it sets the Content-Type response HTTP header field based on the filename extension.

What is Express JSON ()?

json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.

What is RES locals in Express?

The res. locals is an object that contains the local variables for the response which are scoped to the request only and therefore just available for the views rendered during that request or response cycle.


1 Answers

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');
});
like image 59
The Qodesmith Avatar answered Nov 02 '22 07:11

The Qodesmith