在React中,我具有超链接,这些超链接可启动从Express的后端Node服务器获取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)
});
任何输入将不胜感激。
答案 0 :(得分:1)
更新代码,
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']且不是未定义或为空,只是为了在错误侧进行验证。