AWS API Gateway and Lambda to return image

后端 未结 5 2186
情书的邮戳
情书的邮戳 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:39

    I've run in to a similar problem. As mentioned you currently can't directly return your image in binary format from your API Gateway endpoint, which would be required for the browser to display it correctly.

    However, I solved this by instead having API Gateway return a 302 Redirect, pointing to the correct file in S3. You can have your Lambda function return the url to the file, which is later on mapped to the Location header in API Gateway. The browser will follow the redirect and display the image properly.

    There are several ways to implement the redirect, but I did as follow:

    • Lambda returns an object with the target image like so:

      function handler(event, context) {
           context.succeed({ 
               location: "https://[bucket-name].s3-eu-west-1.amazonaws.com/myimage.png" });
           });
      }
      
    • Remove the normal '200' Method Response Status from The Integration Response in API Gateway. Replace it with a '302' response status and add the 'Location' header mapped to value 'integration.response.body.location'

    • Add the 302 status to the Method Response as well

提交回复
热议问题