【问题标题】:Uploading Image from AWS Lambda to S3 via API Gateway in Binary format通过 API 网关以二进制格式将图像从 AWS Lambda 上传到 S3
【发布时间】:2017-12-02 20:25:42
【问题描述】:

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

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

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

请帮忙!

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

【问题讨论】:

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


    【解决方案1】:

    您可以将图像作为节点缓冲区上传到 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);
      });
    };
    

    【讨论】:

    • 附注,使用s3.upload 会为您提供上传文件的URL,s3.putObject 不会
    猜你喜欢
    • 2023-02-22
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 2016-09-02
    • 2020-03-23
    • 2020-01-23
    • 2018-11-09
    • 2018-06-16
    相关资源
    最近更新 更多