如何将PDF文件发送到前端?

时间:2018-03-06 21:28:02

标签: javascript node.js express pdf

我的系统上有一个保存的.PDF文件,我正在尝试使用node / express将文件发送到前端。

我正在将文件作为流(二进制字符串)发送到前端,但是当在前端运行某些代码以将.PDF下载到用户计算机上时,.PDF文件显示为空白。

这是我在服务器上的路线:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<SpecialServiceRQ ReturnHostCommand="false" TimeStamp="2018-03-05T19:02:32.219-05:00" Version="2.2.1" xmlns="http://webservices.sabre.com/sabreXML/2011/10" xmlns:ns2="http://services.sabre.com/STL/v01">
    <SpecialServiceInfo>
        <SecureFlight SegmentNumber="A">
            <PersonName DateOfBirth="1969-02-25" Gender="M" NameNumber="1.1">
                <GivenName>LIAM</GivenName>
                <Surname>JACKSON</Surname>
            </PersonName>
        </SecureFlight>
        <Service SSR_Code="OSI">
            <Text>CTCE/ACCEPT//TEST.CORP.COMPANY.COM</Text>
        </Service>
    </SpecialServiceInfo>
</SpecialServiceRQ>]

[03-05-18 19:02:32.462] [SplitAgentBooker_10009498321_10009498321_2139481603] INFO   SABREpl_timings - : T:0.234 secs S:ABE_ABEBOOKD01_9RVB_000000000002 A:SpecialServiceLLSRS M:2139481603_37114603_37772403_14 RSP: [<?xml version="1.0" encoding="UTF-8"?>
<SpecialServiceRS Version="2.2.1" xmlns="http://webservices.sabre.com/sabreXML/2011/10" xmlns:stl="http://services.sabre.com/STL/v01" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <stl:ApplicationResults status="NotProcessed">
        <stl:Error timeStamp="2018-03-05T18:02:32-06:00" type="BusinessLogic">
            <stl:SystemSpecificResults>
                <stl:Message>.CHECK ENTRY FORMAT.NOT ENT BGNG WITH</stl:Message>
                <stl:Message>3OSI  CTCE/ACCEPT//TEST.CORP.COMPANY.COM</stl:Message>
                <stl:ShortText>ERR.SWS.HOST.ERROR_IN_RESPONSE</stl:ShortText>
            </stl:SystemSpecificResults>
        </stl:Error>
    </stl:ApplicationResults>
</SpecialServiceRS>

以下是前端的代码:

app.post('/someroute', (req, res) => {
  let pdfPath = './somepath/where/the/pdf/is'
  // if the file does not exist
  if (!fs.existsSync(pdfPath)) {
    console.log(`The PDF does NOT exist @ ${pdfPath}`)
    return res.json({ success: false });
  }

  res.download(pdfPath, (err) => {
    if (err) {
      console.log('there was error in res.downoad!', err)
    } else {
      fs.unlink(pdfPath, (err) => {
        if (err) {
          console.log('there was error in unlinking the pdf file!', err)
        } else {
          console.log('success!')
        }
      })
    }
  })
})

这是我在前端收到的流: stream on the frontend

以下是我希望在前端下载的PDF文件:

Expected PDF

以下是实际下载的内容:

Actual downloaded PDF

如果有人能提供任何见解或帮助,我们将非常感谢,谢谢!

1 个答案:

答案 0 :(得分:0)

我认为这对你不起作用的主要原因是因为jQuery不支持&#39; blob&#39;数据类型。

我做了一些研究,并找到了一个如何使用jQuery的例子:

http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/

您需要在博客文章中包含jQuery插件,然后将$ .post调用转换为$ .ajax调用(使用方法POST)并指定传输数据类型为&#39; binary&#39; (加载插件)。

包含插件后,将代码更改为:

    $.ajax({
            method: "POST",
            url: "/someroute",
            dataType: 'binary' // USE THE PLUGIN
        })
        .then(function (data) {
            console.log("Got the PDF file!");

            // Do with the PDF data as you please.

            var downloadLink = document.createElement('a')
            downloadLink.target = '_blank'
            downloadLink.download = 'new_pdf_haha.pdf'
            var blob = new Blob([data], { type: 'application/pdf' })
            var URL = window.URL || window.webkitURL
            var downloadUrl = URL.createObjectURL(blob)
            downloadLink.href = downloadUrl
            document.body.append(downloadLink) // THIS LINE ISN'T NECESSARY
            downloadLink.click()
            document.body.removeChild(downloadLink);  // THIS LINE ISN'T NECESSARY
            URL.revokeObjectURL(downloadUrl);
        })
        .catch(function (err) {
            console.error("An error occurred.");
            console.error(err);
        });

这里有一个完整的工作示例:

https://github.com/ashleydavis/pdf-server-example

请注意,我的服务器设置与您的服务器设置不同,这可能是也可能不是您的问题。我已经包含了用于流式传输和非流式PDF文件下载的示例代码以供比较 - 默认情况下使用流式传输,因为我认为这是您想要的。

另请注意,似乎没有必要将合成链接添加到文档中,并且我已将这些行标记为不必要。

我还应该注意,最好用HTTP GET而不是HTTP POST来做这种事情。如果您这样做,您可以将浏览器下载代码简化为以下内容:

        var downloadLink = document.createElement('a');
        downloadLink.target = '_blank';
        downloadLink.download = 'new_pdf_haha.pdf';
        downloadLink.href = "someroute";
        document.body.append(downloadLink)
        downloadLink.click()
        document.body.removeChild(downloadLink);
相关问题