By using AWS re:Post, you agree to the Terms of Use

File corrupted after upload to S3 using Lambda and API Gateway


Hi people,

I am trying upload the file using Lambda to S3 way API GateWay, i am using the code below, the file is sent to S3 such as show the images 'test_using_postman.png' and 's3_file.png', however when I try open, the show message the file corrupted such as show the 'open_file_with_problem.png'. The images are below.

Somone know the happened ?

Thank you!

Test Using Postman:
S3 File:
Open File with problem:

Code NodeJS:

const crypto = require('crypto');

var AWS = require('aws-sdk');

AWS.config.update({region: 'us-east-1'});

module.exports.arquivo_upload =  (event, context, callback) => {

  let fileContent = event.body;
  let filePath = 'upload/';
  let fileName = crypto.createHash('md5').update('niby_'"hex");

  s3 = new AWS.S3({apiVersion: '2006-03-01'});

  var uploadParams = {
      Bucket: BUCKET_NAME, 
      Key: filePath+fileName+'.png', 
      Body: fileContent,
      ContentType: "image/png"

  s3.upload(uploadParams, function (err, data) {
    if (err) {


        body: JSON.stringify(err),

    } if (data) {;

        body: JSON.stringify(data.Location),

Edited by: LeandroBR on Apr 8, 2020 3:49 PM

asked 2 years ago579 views
1 Answer

I resolved this problem! I sending file using base64 to API Gateway and lambda functions setup parameter "ContentEncoding: 'base64'".

buf = new Buffer(obj.content,'base64')

  let fileName = crypto.createHash('md5').update(config.application_name+'_'"hex");

  s3 = new AWS.S3({apiVersion: config.s3.version});

  var uploadParams = {
      Bucket: config.s3.bucket_name, 
      Key: config.s3.file_path+fileName+obj.extension, 
      Body: buf,
      ContentEncoding: 'base64',
      *ContentType: obj.content_type,*
      ACL: "public-read"

  s3.upload(uploadParams, function (err, data)

Edited by: LeandroBR on Apr 12, 2020 11:47 AM

answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions