我正在尝试使用
Dropzone.js将文件上传到S3服务
https://devcenter.heroku.com/articles/s3-upload-node – 本教程不包含dropzone js的实现(这是一场噩梦)
流程非常简单:
>从我的服务器询问亚马逊的签名
>从亚马逊获取已签名的请求url所需的文件URL
>使用签名的请求网址覆盖dropzone.options.url
>调用dropzone.processFile将文件上传到服务器
文件被上传到服务器,直到这里一切正常,当我试图查看文件时(在S3 Bucket界面中),似乎文件没有正确写入,我无法查看它.
Dropzone.prototype.submitRequest = function(xhr,formData,files) { return xhr.send(formData); }
如果我更改源代码:
xhr.send(formData)
至
xhr.send(files[0])
这是dropzone配置:
{ url: 'http://signature_url',accept: _dropzoneAcceptCallback,method: 'put',headers: { 'x-amz-acl': 'public-read','Accept': '*/*','Content-Type': file.type },clickable: ['.choose-files'],autoProcessQueue: false }
希望它够了:)
谢谢.
@R_403_323@
对于那些也可能会涉及这个问题的人,我也想分享我的工作实例.请注意,我更进一步,取消了自己的后端并使用AWS Lambda(又名无服务器)来代替签名工作,但概念是相同的.
架构
基本上,
>您正在签署一个PUT可上传的URL,因此您必须如您所述劫持xhr.send函数.
>您可以在accept函数中调用processFile,而不是依赖Dropzone的FormData来上传多个文件.因此,对于每个被接受的文件,上传将立即开始,您可以同时上传多个文件.
最终的客户端代码
const vm = this let options = { // The URL will be changed for each new file being processing url: '/',// Since we're going to do a `PUT` upload to S3 directly method: 'put',// Hijack the xhr.send since Dropzone always upload file by using formData // ref: https://github.com/danialfarid/ng-file-upload/issues/743 sending (file,xhr) { let _send = xhr.send xhr.send = () => { _send.call(xhr,file) } },// Upload one file at a time since we're using the S3 pre-signed URL scenario parallelUploads: 1,uploadMultiple: false,// Content-Type should be included,otherwise you'll get a signature // mismatch error from S3. We're going to update this for each file. header: '',// We're going to process each file manually (see `accept` below) autoProcessQueue: false,// Here we request a signed upload URL when a file being accepted accept (file,done) { lambda.getSignedURL(file) .then((url) => { file.uploadURL = url done() // Manually process each file setTimeout(() => vm.dropzone.processFile(file)) }) .catch((err) => { done('Failed to get an S3 signed upload URL',err) }) } } // Instantiate Dropzone this.dropzone = new Dropzone(this.$el,options) // Set signed upload URL for each file vm.dropzone.on('processing',(file) => { vm.dropzone.options.url = file.uploadURL })
上面的代码有一些与Vue.js相关的东西,但这个概念实际上是框架无关的,你明白了.有关完整工作的dropzone组件示例,请查看my GitHub repo.
演示