React + Node / Express |在React中渲染PDF二进制流blob

问题描述 投票:0回答:1

在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)
});

任何输入都将非常感激。

javascript node.js reactjs blob fetch
1个回答
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']并且未定义或为空以仅在错误方面进行验证。

© www.soinside.com 2019 - 2024. All rights reserved.