[英]File corrupted after upload to S3 using Lambda and API Gateway
我正在嘗試使用 Lambda 將文件上傳到 S3 方式 API GateWay,我正在使用下面的代碼,文件被發送到 S3,例如顯示圖像“test_using_postman.png”和“s3_file.png”,但是當我嘗試打開時,顯示文件損壞的消息,例如顯示“open_file_with_problem.png”。 圖片如下。
有人知道發生了什么嗎?
謝謝!
圖片:
使用 Postman 進行測試: 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 網關和 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"
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.