Get an object from S3 in AWS Lambda function and send to Api Gateway

I am trying to get a .jpg file from a bucket and send it back to the api gateway. I believe that I have the correct setting, because I see that the material is being recorded. It captures a file with s3 fine, and gm is a graphics library. Not sure if I am using this correctly.

In lambda function, I do this (a lot of code from aws example):

async.waterfall([ function download(next) { console.log(srcKey); console.log(srcBucket); // Download the image from S3 into a buffer. s3.getObject({ Bucket: srcBucket, Key: srcKey }, next); }, function transform(response, next) { console.log(response); next(null, 'image/jpeg', gm(response.Body).quality(85)); }, function sendData(contentType, data, next){ console.log(contentType); console.log(data); imageBuffer = data.sourceBuffer; context.succeed(imageBuffer); } ] ); 

The response header has a content length of 85948, which seems incorrect because the source file is only 36 kB. Does anyone know what I'm doing wrong?

+5
source share
2 answers

You can easily achieve integration with Get Image โ†” API Gateway โ†” Lambda โ†” S3.

In lambda, instead of json, return the string representation of the base64 image ( buffer.toString('base64') ), make the Gateway API convert the string to binary and add a specific Content-Type (so you don't need limited binary support that forces you to send a specific header Accept).

In the AWS console, go to the Gateway API, then go to the appropriate method and update the settings:

  • Integration Request

    • Uncheck: Use integration with Lambda Proxy
  • Method Answer

    • Add Answer โ†’ HTTP Status: 200
    • Add Header: Content-Type
  • Integration Response โ†’ Title Mapping โ†’ Response Header โ†’ Content Type

    • Matching value: 'image / jpeg' (single quote question)

From the command line, run the command below to force the conversion of the string to binary. First, get rest-api-id and resource-id from the API gateway. Then run in the CLI (replace rest-api-id and resource identifier with your own):

 aws apigateway put-integration-response --rest-api-id <rest-api-id> --resource-id <resource-id> --http-method GET --status-code 200 --content-handling CONVERT_TO_BINARY 
+4
source

You should not use API Gateway to transfer binary content when using it with Lambda . API Gateway with Lambda configured to respond with XML/JSON data. Learn more about why and how here .

Try changing the callback chain to load the changed image back into S3 . After a successful download, send the URI target and redirect your client to it.

+2
source

All Articles