Send a PDF generated from an API to an external server?

我与影子孤独终老i 提交于 2021-01-28 08:27:05

问题


I have a NodeJS-ExpressJS server (to host a web page) and Django API server. When a specific endpoint in the Django server is called from the ExpressJS server (when a user clicks a button on the web page), a PDF is generated. I want to send this PDF from the Django server to the ExpressJS server and then download it to the user's browser (The user only interfaces with ExpressJS server). In order to do this I encode the PDF as a base64 string in the Django server and return the string in an HTTP response. In the ExpressJS server, I decode the base64 string and then use the res.download() method provided by the ExpressJS framework to download the PDF to the user's browser. This method appears to work, but can it corrupt the PDF file? Is there a way to simply send the PDF file as a binary file and download it to the browser that way (If possible, please provide an example)? Any answers, examples, and suggestions are greatly appreciated.

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

回答1:


I think your code is bulky and buffers up the entire file.pdf into memory (body) for every request before writing the result back to clients, it could start eating a lot of memory if there were many requests at the same time, that's why you should use streams:

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

});

By using streams the program will read file.pdf one chunk at a time, store it into memory and send it back to the client.



来源:https://stackoverflow.com/questions/48191460/send-a-pdf-generated-from-an-api-to-an-external-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!