【问题标题】:Send a PDF generated from an API to an external server?将 API 生成的 PDF 发送到外部服务器?
【发布时间】:2018-06-19 20:40:54
【问题描述】:

我有一个 NodeJS-ExpressJS 服务器(用于托管网页)和 Django API 服务器。当从 ExpressJS 服务器调用 Django 服务器中的特定端点时(当用户单击网页上的按钮时),将生成 PDF。我想将此 PDF 从 Django 服务器发送到 ExpressJS 服务器,然后将其下载到用户的浏览器(用户仅与 ExpressJS 服务器交互)。为了做到这一点,我在 Django 服务器中将 PDF 编码为 base64 字符串,并在 HTTP 响应中返回该字符串。在 ExpressJS 服务器中,我对 base64 字符串进行解码,然后使用 ExpressJS 框架提供的res.download() 方法将 PDF 下载到用户的浏览器。此方法似乎有效,但它会损坏 PDF 文件吗?有没有办法简单地将 PDF 文件作为二进制文件发送并以这种方式下载到浏览器(如果可能,请提供示例)?非常感谢任何答案、示例和建议。

Django API server
def process_upload(request):
   '''
   Process request and generate PDF
   ....
   '''
   with open(pdf, "rb") as pdf_file:
     encoded_string = base64.b64encode(pdf_file.read())
     return HttpResponse(encoded_string)

ExpressJS server
server.get('/api', function(req, res, next) {
  request.post({
     url: 'http://<api_url>',
     oauth: oauth,
     preambleCRLF: true,
     postambleCRLF: true
   }, function(error, response, body){
      res.writeHead(200, {
        'Content-Type': 'application/pdf',
        'Content-Disposition': 'attachment; filename="file.pdf"' 
      });
   });
   const download = Buffer.from(body.toString('utf-8'), 'base64');
   res.end(download);
 });  

【问题讨论】:

    标签: python node.js django express pdf


    【解决方案1】:

    我认为您的代码很庞大,并且在将结果写回客户端之前将每个请求的整个 file.pdf 缓冲到内存 (body) 中,如果有很多请求,它可能会开始占用大量内存同时,这就是你应该使用流的原因:

    server.get('/apisd', function(req, res, next) {
    
        // Force browser to download file
        res.set('Content-Type', 'application/pdf');
        res.set('Content-Disposition', 'attachment; filename=file.pdf');
    
        // send file
        request.post({
            url: 'http://<api_url>',
            oauth: oauth,
            preambleCRLF: true,
            postambleCRLF: true
        }).pipe(res);
    
    });
    

    通过使用流,程序将一次读取file.pdf 一个块,将其存储到内存中并将其发送回客户端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      相关资源
      最近更新 更多