How do I send a binary response with AWS Lambda with API Gateway in Node.js?

10,470

Solution 1

I found my answer here: AWS Gateway API base64Decode produces garbled binary?

It requires a CLI command to change a setting that isn't exposed in the AWS Console when you select Lambda Function on the Create Method screen.

Solution 2

Did you read this blog post?

Please follow those instructions and ensure your client is correctly sending the Content-Type and Accept headers

Share:
10,470
tkiethanom
Author by

tkiethanom

Code Space Astronaut

Updated on June 05, 2022

Comments

  • tkiethanom
    tkiethanom almost 2 years

    I'm trying to set up a Lambda and API Gateway that will do a s3.getObject() and output the binary image as a response. Eventually I'd like to pull an image from s3 and resize on the fly instead of saving them back to s3, however I can't seem to get even a simple image to output.

    My simple lambda looks like this:

    'use strict';
    
    const http = require('http');    
    
    exports.handler = (event, context, callback) => {
        http.get('http://i.stack.imgur.com/PIFN0.jpg', function(res) {
            var body = '';
            res.on('data', function(chunk) {
                // Agregates chunks
                body += chunk;
            });
            res.on('end', function() {
                callback(null, body);
            });
        });    
    };
    

    I've set the API Gateway Binary Support to allow 'image/jpeg' and I've tried setting the Content Type in the Method Response and Integration Response.

    Method Response: enter image description here

    Integration Response: enter image description here

  • tkiethanom
    tkiethanom over 7 years
    That blog post example is for a binary upload which I've done successfully but I haven't been able to display a binary image through a lamba. There is also this article but it doesn't use a lambda. docs.aws.amazon.com/apigateway/latest/developerguide/…
  • RyanG
    RyanG over 7 years
    The blog post demonstrates a binary response of a thumbnail image from API Gateway/Lambda, which I think is very similar to what you are trying to do.