首页 > 解决方案 > 反应 + 节点/快递 | 在 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)
});

任何输入将不胜感激。

标签: javascriptnode.jsreactjsblobfetch

解决方案


更新您的代码,

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'] 并且不是未定义或为空,只是为了在错误方面进行验证。


推荐阅读