javascript - 反应 + 节点/快递 | 在 React 中渲染 PDF 二进制流 blob
问题描述
在 React 中,我有超链接,它们使用 Express 从后端节点服务器启动对 PDF 文件的获取。问题是流打开了一个新的二进制文本窗口,而不是 PDF 文件。
反应前端:
//Link
<a href={'#'} onClick={() => this.renderPDF(row.row.pdfid)}> {row.row.commonName}.pdf</a>
//Fetch call
renderPDF = (pdfLink) => {
fetch('http://localhost:8000/pdf' + '?q=' + pdfLink, {
method: 'GET'
//credentials: 'include'
})
.then(response => response.blob())
.then(blob => URL.createObjectURL(blob))
.then(url => window.open(url))
.catch(error => this.setState({
error,
isLoading: false
}));
}
节点后端:
app.get('/pdf', (req, res) => {
let readStream = fs.createReadStream(req.query["q"]);
let chunks = [];
// When the stream is done being read, end the response
readStream.on('close', () => {
res.end()
})
// Stream chunks to response
readStream.pipe(res)
});
任何输入将不胜感激。
解决方案
更新您的代码,
app.get('/pdf', (req, res) => {
let readStream = fs.createReadStream(req.query["q"]);
let stat = fs.statSync(req.query["q"]);
// When the stream is done being read, end the response
readStream.on('close', () => {
res.end()
})
// Stream chunks to response
res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'inline; filename=test.pdf');
readStream.pipe(res);
});
现在试试这个。此外,检查您是否获得查询 ['q'] 并且不是未定义或为空,只是为了在错误方面进行验证。
推荐阅读
- android - 当应用程序在android上恢复时,React Native StatusBar translucent 未设置为true
- ansible - Ansible:按特定字段比较两个数组
- php - 使用 php 的 Wordpress 自定义小部件
- r - 如何处理具有不同长度的列表?
- r - 使用 reshape 包重塑数据库
- azure-data-factory-2 - 无法在复制数据工具中连接到 SFTP(带有私钥文件)
- python - Numpy矢量化:查找列表和列表列表之间的交集
- angular - 角度编译错误“NgModule”调用“ɵmakeDecorator”
- python - 为python目录中的每个.pdf文件创建一个新的.txt文件
- vuejs2 - 加载来自 vuex 存储的所有计算数据后如何加载数据?