通过二进制格式的API网关将映像从AWS Lambda上传到S3

时间:2017-06-29 08:28:58

标签: node.js file-upload amazon-s3 aws-lambda aws-sdk

我的Lambda正在请求正文(event.body)中接收用户的二进制数据。

我尝试将其上传到S3时没有错误,但是当我下载时,图片已损坏/无法打开。

我还需要将上传图片的URl返回给用户。

请帮助!

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 个答案:

答案 0 :(得分:4)

您可以将图像作为节点缓冲区上传到S3。 SDK会为您进行转换。

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);
  });
};
相关问题