File corrupted after upload to S3 using Lambda and API Gateway

0

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!

Images:
Test Using Postman: https://drive.google.com/open?id=1eenEnvuMQU28iI_Ltqzpw9OlCvIcY5Fg
S3 File: https://drive.google.com/open?id=1b1_CmIhzfc8mQj_rwCK6Xy30gzoP6HcK
Open File with problem: https://drive.google.com/open?id=1o54rLB9wWF1KxdUOkq3xAGVET7UWoqgf

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 BUCKET_NAME = 'XXXXX';

  let fileContent = event.body;
  let filePath = 'upload/';
  let fileName = crypto.createHash('md5').update('niby_'+Date.now()).digest("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) {

      console.error(err);

      callback(null,{
        statusCode:400,
        body: JSON.stringify(err),
      });

    } if (data) {

      console.info(data.Location);

      callback(null,{
        statusCode:200,
        body: JSON.stringify(data.Location),
      });
    }
  });
}

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

gefragt vor 4 Jahren4265 Aufrufe
1 Antwort
0

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+'_'+Date.now()).digest("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

beantwortet vor 4 Jahren

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen