AWS API GATEWAY configuration to return binary pdf file from lambda

孤街浪徒 提交于 2021-01-27 11:58:22

问题


I want to return a pdf from a AWS Lambda function, and I use API Gateway for calling it from a any browser.

I have a aws lambda function in c# that returns an API Gateway Response which body is a pdf in base64 encoded string.

So far the endpoint returns a file with .pdf extension but not in binary. Instead, is a text file with the base64 string.

The headers i'm returning from the c# code are:

  var headersDic = new Dictionary<string, string>();
      headersDic.Add("Content-type", "application/pdf");
      headersDic.Add("Content-disposition", "attachment; filename=file.pdf");

I converted manually the base64 string to binary file and opened it as a pdf, and it works, I mean, the base64 string is correct so I assume the problem is being the API Gateway.

In the integration response console of the API Gateway, I got this:

But i'm not able to make it work.

I also have binary media types enabled.


回答1:


I don't know exactly what I did, but I deleted the 'ALL' method, and created the 'GET' method with this config and now it works.




回答2:


You also need to declare the content type like the following in your LambdaEntryPoint.cs

See this documentation: https://github.com/aws/aws-lambda-dotnet/blob/master/Libraries/src/Amazon.Lambda.AspNetCoreServer/README.md

You have to tell Lambda you're going to return something besides strings.

public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
{

    protected override void Init(IWebHostBuilder builder)
    {
        builder
            .UseStartup<Startup>();

        ****IMPORTANT PART HERE****
        RegisterResponseContentEncodingForContentType("application/pdf",
            ResponseContentEncoding.Base64);
    }
}



回答3:


Response Headers

'Content-Type': 'application/pdf'
'Content-disposition', 'attachment; filename=fileName.pdf'

Response to Client

{
 statusCode: 200
 headers: responseHeader,
 body: pdfContent.toString(base64),
 isBase64Encoded: true,
}

API Gateway Binary Media Types

Hope it will help



来源:https://stackoverflow.com/questions/52156418/aws-api-gateway-configuration-to-return-binary-pdf-file-from-lambda

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