使用单个Lambda函数将多个文件类型上传到S3



我希望用户能够将JPG或PNG图像上传到S3存储桶。

我使用的是Lambda函数,它只允许我为S3预签名.jpg图像,而且它只适用于一种文件类型。如何添加额外的文件类型进行预签名,例如.png图像。我真的需要写一个新的Lambda吗?我只需将.jpg更改为.png,或者我可以在下面现有的代码中以某种方式完成它?

const AWS = require('aws-sdk')
AWS.config.update({ region: process.env.REGION })
const s3 = new AWS.S3();
const uploadBucket = 'xxx-bucket'
exports.handler = async (event) => {
const result = await getUploadURL()
console.log('Result: ', result)
return result
};
const getUploadURL = async function() {
console.log('getUploadURL started')
let actionId = Date.now()
var s3Params = {
Bucket: uploadBucket,
Key:  `${actionId}.jpg`,
ContentType: 'image/jpeg',
CacheControl: 'max-age=31104000',
ACL: 'public-read',
};
return new Promise((resolve, reject) => {
// Get signed URL
let uploadURL = s3.getSignedUrl('putObject', s3Params)
resolve({
"statusCode": 200,
"isBase64Encoded": false,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": JSON.stringify({
"uploadURL": uploadURL,
"photoFilename": `${actionId}.jpg`
})
})
})
}

您的选项如下:

  • 按照您的建议制作一个新的Lambda,以单独处理PNG
  • 通过事件将参数传递给getUploadURL函数,例如:
exports.handler = async event => {
const { filetype } = event.body (or pathParams, query string, etc)
const result = await getUploadURL(filetype)
console.log('Result: ', result)
return result
};
const getUploadURL = async filetype => {
console.log('getUploadURL started')
let actionId = Date.now()
var s3Params = {
Bucket: uploadBucket,
Key:  `${actionId}.${filetype}`,
ContentType: `image/${filetype === 'jpg'?'jpeg':'png'}`,
CacheControl: 'max-age=31104000',
ACL: 'public-read',
};
...

对S3.getSignedUrl((的调用对于putObject操作至少需要{Bucket: 'bucket', Key: 'key'}。因此,如果您不想牺牲文件扩展名和/或内容类型属性,这些是唯一的选择。

AWS文档

相关内容

  • 没有找到相关文章

最新更新