请帮助实现 dropzone.js 将文件上传到 Amazon s3 服务器。已经参考了以下链接https://github.com/enyo/dropzone/issues/33 https://github.com/enyo/dropzone/issues/33,但是,没有想法实施。请帮助实施同样的措施。需要任何 dropzone 配置代码。
对于可能也提出这个问题的人,我想分享我的工作场景(使用 AWS Lambda 无服务器)。
Note:完整的例子可以在我的Vue S3 Dropzone 组件 https://github.com/kfei/vue-s3-dropzone/blob/master/frontend/src/components/Dropzone.vue,与 Dropzone 和 S3 相关的代码实际上与框架无关。
所以,基本上,
- 客户端(浏览器)调用 AWS Lambda 函数来获取要添加的每个文件的预签名上传 URL。
- 当预签名 URL 作为响应返回时,客户端将触发
dropzone.processFile
立即地。
- 当文件正在处理时,改变
dropzone.options.url
相应的文件。
Hints:
- 当我签署一份PUT可上传的网址,我要去hijack https://github.com/kfei/vue-s3-dropzone/blob/e348188/frontend/src/components/Dropzone.vue#L30-L37 the
xhr.send
函数,否则 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 })
}
})
}
Demo
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)