0

Attempting to upload an image from a lambda into an S3 bucket, and every time I run a test, the image in the S3 bucket is empty, only being a couple kb large.

const AWS = require('aws-sdk'); 
var s3 = new AWS.S3();
exports.handler = (event, context, callback) => {
    console.log(event);
     let encodedImage =JSON.parse(event.body).image;
     let fileType = encodedImage.match(/[^:/]\w+(?=;|,)/)[0];
     let decodedImage = Buffer.from(encodedImage, 'base64');
     var filePath = "posts/" + JSON.parse(event.body).imageID + "." + fileType
     var params = {
       "Body": decodedImage,
       "Bucket": "ccarlson-blog-images",
       "Key": filePath  
    };
    s3.upload(params, function(err, data){
       if(err) {
           callback(err, null);
       } else {
           let response = {
        "statusCode": 200,
        "headers": {
            "my_header": "my_value"
        },
        "body": JSON.stringify(data),
        "isBase64Encoded": false
    };
           callback(null, response);
    }
    });

};

The request I'm sending via postman is as follows

{
    "image": "data:image/png;base64,iVBORw0KGgoAAAANSU...etc",
    "imageID": "4651656516216546"
}

The fact that it is properly putting something in S3 leads me to believe the issue is in my decodedImage variable, but I'm unsure of what I could be doing wrong there. Any help is appreciated!

ccarlson
  • 13
  • 2
  • Try adding `ContentEncoding: 'base64'` to params. – jellycsc May 13 '20 at 13:48
  • Thanks, I gave that a try, and it didn't make a difference. I then went in and changed it according to the answer on [this question](https://stackoverflow.com/questions/7511321/uploading-base64-encoded-image-to-amazon-s3-via-node-js), updating the depreciated buffer method, but I'm still getting the same results, an empty image. – ccarlson May 14 '20 at 03:48
  • Hey did you figure this out? – ph-quiett Nov 11 '22 at 19:19
  • It's been a long while since I had this issue but if I remember correctly, this code was correct. The first time I uploaded, it was the correct size, but corrupt, so when the other uploads, that ended up being correct, were the same size, I didn't even check them, but they were uploading correctly. Hope that helps! – ccarlson Nov 12 '22 at 20:04

0 Answers0