Ale*_*nov 5 streaming download node.js express
当我通过管道传输响应时,有什么方法可以强制下载吗?如果我查看 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
Run Code Online (Sandbox Code Playgroud)
我什至在详细响应中看到了 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)
});
});
Run Code Online (Sandbox Code Playgroud)
您需要添加一个Content-Disposition标头来向浏览器发出信号,表明有附加的内容需要下载。
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)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3372 次 |
| 最近记录: |