AWS API Gateway and Lambda to return image

后端 未结 5 2191
情书的邮戳
情书的邮戳 2021-02-19 06:02

Say I have this HTML:


What I would like to do is have example.com/pic map to an AWS API Gateway end

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 06:58

    It seems AWS has simplified this process, so that many answers are outdated and/or overly complicated.

    This is how I got Lambda to return an image through the API Gateway, as of June 2018:

    1) In API Gateway, enable Use Lambda Proxy integration for your API. (This setting is located on the Integration Request section, where you had set the type to Lambda.)

    2) In API Gateway, select your API and click Settings. In Binary Media Types add */*. (Note: I tried adding simply 'image/jpeg', but it seems to require */* to get all of this to work)

    3) Be sure to deploy your API, otherwise your changes will not be live. (In API Gateway, select your API, then Actions > Deploy API).

    4) In your Lambda code, return your image in Base64 encoding (this example is C# code):

        // set the Content-type header
        // set to whichever image type you're returning
        var headersDic = new Dictionary();
        headersDic.Add("Content-type", "image/jpeg");
    
        // return the response object that APIGateway requires
        return new APIGatewayProxyResponse
        {
            StatusCode = 200,
            Headers = headersDic,
            // return the image in Base64 encoding
            Body = Convert.ToBase64String(...your image data...),
            IsBase64Encoded = true
        };
    

    Done.

    If you've setup your API to not require authentication, simply type your API link into your browser, and it will display the image. Or put the API link into an IMG tag. e.g.

    Note: Even though in step 2 you set the Binary Media Types to */*, API Gateway will still return text if that is what your Lambda is returning.

提交回复
热议问题