amazon-web-services - 使用 Lambda 和 API 网关上传到 S3 后文件损坏
问题描述
我正在尝试使用 Lambda 将文件上传到 S3 方式 API GateWay,我正在使用下面的代码,文件被发送到 S3,例如显示图像“test_using_postman.png”和“s3_file.png”,但是当我尝试打开时,显示文件损坏的消息,例如显示“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),
});
}
});
}
解决方案
我解决了这个问题!我使用 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"
};
推荐阅读
- python - 在单独的文件中搜索数据库
- c# - 如何在c#中处理队列数据
- javascript - 从 ISOString 中 .slice() 时间子串的安全(与格式无关)方式
- java - Maven 无法解析来自私有关系的依赖项
- python - 如何在 python 中使用 service = build('gmail', 'v1', http=creds.authorize(Http())) 而不是 service = build('gmail', 'v1', credentials=creds)
- python - 如何使用 Matplotlib 获得 N 种易于区分的颜色
- azure - Azure Cosmos DB - '请求率很大。删除项目时可能需要更多请求单位的错误
- c# - C# API 调用另一个 api 失败,并显示“远程证书根据验证过程无效”
- python - 如何在 Python 的输入中读取多行?
- reactjs - react-leaflet hides a drop down menu