2

My Lambda is receiving binary data of an image from my user in request body (event.body).

I try uploading it to S3 with no error, but when I download, the image is corrupted/ can't be opened.

I also need to return the URl of the uploaded image to the user.

Please Help!

module.exports.uploadImage = (event, context, callback) => {
  var buf = new Buffer(new Buffer(event.body).toString('base64').replace(/^data:image\/\w+;base64,/, ""),'base64');
  var data = {
    Key: Date.now()+"", 
    Body: buf,
    ContentEncoding: 'base64',
    ContentType: 'image/png',
    ACL: 'public-read'
  };
  s3Bucket.putObject(data, function(err, data){
      if (err) { 
        console.log(err);
        console.log('Error uploading data: ', data); 
      } else {
        console.log('succesfully uploaded the image!');
      }
      callback(null,data);
  });
};

1 Answer 1

8

You can upload the image to S3 as node Buffer. The SDK does the converting for you.

const AWS = require("aws-sdk");
var s3 = new AWS.S3();

module.exports.handler = (event, context, callback) => {
  var buf = Buffer.from(event.body.replace(/^data:image\/\w+;base64,/, ""),"base64");
  var data = {
    Bucket: "sample-bucket", 
    Key: Date.now()+"", 
    Body: buf,
    ContentType: 'image/png',
    ACL: 'public-read'
  };
  s3.putObject(data, function(err, data){
      if (err) { 
        console.log(err);
        console.log('Error uploading data: ', data); 
      } else {
        console.log('succesfully uploaded the image!');
      }
      callback(null,data);
  });
};
Sign up to request clarification or add additional context in comments.

1 Comment

side note, using s3.upload gives you the URL of the uploaded file, s3.putObject does not

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.