AWS Lambda fails to return PDF file

穿精又带淫゛_ 提交于 2019-12-18 15:48:22

问题


I have created a lambda function using serverless. This function is fired via API Gateway on a GET request and should return a pdf file from a buffer. I'm using html-pdf to create the buffer and trying to return the pdf file with the following command

  let response = {
    statusCode: 200,
    headers: {'Content-type' : 'application/pdf'},
    body: buffer.toString('base64'),
    isBase64Encoded : true,
  };
  return callback(null, response);

but the browser is just failing to load the pdf, so I don't know exactly how to return the pdf file directly to the browser. Could'nt find a solution for that.


回答1:


well, I found the answer. The settings in my response object are fine, I just had to manually change the settings in API Gateway for this to work in the browser. I have added "*/*" to binary media types under the binary settings in API Gateway console

API GATEWAY

  1. just log into your console
  2. choose your api
  3. click on binary support in the dropdown
  4. edit binary media type and add "*/*"

FRONTEND

opening the api url in new tab (target="_blank"). Probably the browser is handling the encoded base 64 response, In my case with chrome, the browser just opens the pdf in a new tab exactly like I want it to do.




回答2:


After spending several hours on this I found out that if you set Content handling to Convert to binary (CONVERT_TO_BINARY) the entire response has to be base64, I would otherwise get an error: Unable to base64 decode the body.

Therefore my response now looks like:

callback(null, buffer.toString('base64'));

The Integration response:

The Method response:

And Binary Media Types:




回答3:


If you have a gigantic PDF, then it will take a long time for Lambda to return it and in Lambda you are billed per 100ms.

I would save it to S3 first then let the Lambda return the S3 url to the client for downloading.




回答4:


Above solution is only for particular content-type. You can't more content type. Follow only below two-step to resolve multiple content type issue.

  1. Click on the checkbox of Use Lambda Proxy integration

API gateway --> API --> method --> integration request

  1. Create your response as

        let response = {
    
          statusCode: 200,
          headers: {
            'Content-type': 'application/pdf',//you can change any content type
            'content-disposition': 'attachment; filename=test.pdf' // key of success
          },
          body: buffer.toString('base64'),
          isBase64Encoded: true
        };
        return response;
    

Note* - It is not secure



来源:https://stackoverflow.com/questions/45348580/aws-lambda-fails-to-return-pdf-file

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