Reputation: 607
Is there any way to force download when i pipe stream to response? If I look into Chrome tools, I see that response is OK, with fine headers:
HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/pdf
Date: Mon, 10 Oct 2016 20:22:51 GMT
Transfer-Encoding: chunked
Via: 1.1 vegur
Request Headers
view source
I even see the pdf file code in detailed response, but no file download is initiated. Maybe I miss something?
My code on route looks like:
router.post('/reports/create', access.Regular, function (req, res, next) {
...
pdf.create(html).toBuffer(function(err, buffer){
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename=some_file.pdf',
'Content-Length': buffer.length
});
res.end(buffer)
});
});
Upvotes: 5
Views: 3549
Reputation: 1
it works for me like this:
var html = '<h1>Hello World</h1>';
let options = {
format: 'Letter',
border: '1cm'
};
pdf.create(html, options).toBuffer(function (err, Buffer) {
if (err) {
res.json({
data: 'error PDF'
})
} else {
res.set({
'Content-Disposition': 'attachment; filename=test.pdf',
'Content-Type': 'application/pdf; charset=utf-8'
});
res.write(Buffer);
res.end();
}
});
Upvotes: 0
Reputation: 19418
You need to add a Content-Disposition
Header to signal to the browser that there is content attached that needs to be downloaded.
app.get('/:filename', (req, res) => {
// Do whatever work to retrieve file and contents
// Set Content-Disposition Header on the response
// filename is the name of the file the browser needs to download when
// receiving the response to this particular request
res.setHeader('Content-Disposition', `attachment; filename=${req.params.filename}`);
// stream the fileContent back to the requester
return res.end(fileContent)
});
Upvotes: 2