【问题标题】:React + Node/Express | Rendering a PDF binary stream blob in React反应 + 节点/快递 |在 React 中渲染 PDF 二进制流 blob
【发布时间】:2019-01-29 09:26:07
【问题描述】:

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

任何意见将不胜感激。

【问题讨论】:

  • 什么是readStream?它是在哪里定义的?
  • 我编辑了帖子以突出显示重要的内容。

标签: javascript node.js reactjs blob fetch


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

【讨论】:

  • 我没有使用 readFile,我正在使用 readStream 做一个文件流。我的文件会很大,所以我不想将整个文件加载到内存中,而是使用块。
  • 成功了!太感谢了!抱歉,我以为 res.setHeader 语句是特定于 readFile
  • 抱歉,我的账户还没有解锁点赞。
  • 不用担心。解决的问题是我的赞成票。不用担心。
猜你喜欢
  • 1970-01-01
  • 2017-01-22
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
  • 1970-01-01
  • 2021-01-14
  • 2022-10-09
相关资源
最近更新 更多