I can't for the life of me get a download dialog to pop up instead of just directly downloading a file in my node application.
My troubled code looks like this:
app.get(`/search/download`, function(req, res){
var request = require(`request`);
request({uri: `http://some.csv.file`, headers: {`content-type`: `text/csv`}}
, function(err, response, body) {
res.set(`Content-Disposition`, `attachment; filename="search-results.csv"`);
res.set(`Content-Type`, `text/csv`);
res.send(body);
});
}
No matter what I change, both Chrome and Safari immediately download the file instead of bringing up a save dialog box.
Change the Content-Type from text/csv to application/octet-stream.
app.get(`/search/download`, function(req, res){
var request = require(`request`);
request({uri: `http://some.csv.file`, headers: {`content-type`: `text/csv`}}
, function(err, response, body) {
res.set(`Content-Disposition`, `attachment; filename="search-results.csv"`);
res.set(`Content-Type`, `application/octet-stream`);
res.send(body);
});
}
There is an easier way to do the same thing (if the served file is static):
app.use(express.static(__dirname + '/some.csv.file', {
setHeaders: function(res, path) {
res.set('Content-Disposition', 'attachment; filename="search-results.csv"');
res.set('Content-Type', 'application/octet-stream');
}
})