对于可能也会跳到这个问题的人,我想分享我的工作场景(无服务器与AWS Lambda).
注意:在我的Vue S3 Dropzone component中可以找到完整的示例,与Dropzone和S3相关的代码实际上与框架无关.
基本上,
>客户端(浏览器)调用AWS Lambda函数以获取要添加的每个文件的预签名上载URL.
>当响应中返回预签名URL时,客户端将立即触发dropzone.processFile.
>当正在处理文件时,相应地更改文件的dropzone.options.url.
>当我正在签署一个PUT上传URL时,我将使用xhr.send函数hijack,否则Dropzone将始终在formData中发送文件,这对于PUT上传是不利的.
最终的客户端代码
// In the `accept` function we request a signed upload URL when a file being accepted
accept (file,done) {
lambda.getSignedURL(file)
.then((url) => {
file.uploadURL = url
done()
// And process each file immediately
setTimeout(() => dropzone.processFile(file))
})
.catch((err) => {
done('Failed to get an S3 signed upload URL',err)
})
}
// Set signed upload URL for each file being processing
dropzone.on('processing',(file) => {
dropzone.options.url = file.uploadURL
})
最终的AWS Lambda代码
var AWS = require('aws-sdk')
var s3 = new AWS.S3();
// Make sure you set this env variable correctly
var bucketName = process.env.AWS_BUCKET_NAME
exports.handler = (event,context) => {
if (!event.hasOwnProperty('contentType')) {
context.fail({ err: 'Missing contentType' })
}
if (!event.hasOwnProperty('filePath')) {
context.fail({ err: 'Missing filePath' })
}
var params = {
Bucket: bucketName,Key: event.filePath,Expires: 3600,ContentType: event.contentType
}
s3.getSignedUrl('putObject',params,(err,url) => {
if (err) {
context.fail({ err })
} else {
context.succeed({ url })
}
})
}
演示