使用Lambda和API Gateway上传到S3后文件损坏

时间:2020-04-09 01:44:56

标签: amazon-web-services amazon-s3 aws-lambda aws-api-gateway

我正在尝试使用Lambda将文件上传到S3方式API GateWay,我正在使用下面的代码,文件被发送到S3,例如显示图像'test_using_postman.png'和's3_file.png',但是当我尝试打开后,显示消息文件已损坏,例如show'open_file_with_problem.png'。图片在下面。

有人知道发生了什么吗?

谢谢!

图片:

使用邮递员进行测试:https://drive.google.com/open?id=1eenEnvuMQU28iI_Ltqzpw9OlCvIcY5Fg

S3文件:https://drive.google.com/open?id=1b1_CmIhzfc8mQj_rwCK6Xy30gzoP6HcK

打开文件时出现问题:https://drive.google.com/open?id=1o54rLB9wWF1KxdUOkq3xAGVET7UWoqgf

代码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) {

      //TODO: Call other api to save file name

      console.info(data.Location);

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

1 个答案:

答案 0 :(得分:0)

我解决了这个问题!我使用base64将文件发送到API Gateway和lambda函数设置参数“ ContentEncoding:'base64'”。

  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"
};