当我通过流响应时,有什么方法可以强制下载?
如果我查看Chrome工具,会发现响应很好,标题也不错:
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
我什至在详细响应中都看到了pdf文件代码,但是没有启动文件下载。也许我想念什么?
我的路线代码如下:
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)
});
});
最佳答案
您需要添加 Content-Disposition
header ,以向浏览器发出信号,表明需要下载附件。
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)
});
关于node.js - Node/Express:stream.pipe()上没有下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39966311/