2017-06-29 57 views
0

我的Lambda从我的用户身上接收图像的二进制数据(event.body)。通过API Gateway以二进制格式将图像从AWS Lambda上传到S3

我尝试上传到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); 
    }); 
}; 

回答

2

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

注意,使用's3upload'给你上传的文件的URL,'s3.putObject'没有 –