我正在尝试使用Dropzone.js将文件上传到S3服务
我使用本教程直接从客户端上传文件:
https://devcenter.heroku.com/articles/s3-upload-node-本教程不包含dropzone js的实现(这是一场噩梦)
流程非常简单:
从我的服务器询问亚马逊的签名
获取已签名的请求网址+来自亚马逊的预期文件网址
使用签名的请求网址覆盖dropzone.options.url
调用dropzone.processFile将文件上传到服务器
文件被上传到服务器,直到这里一切正常,当我试图查看文件时(在S3 Bucket界面中),似乎文件没有正确写入,我无法查看它.
根据源代码,使用FormData对象上传文件.
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 }
希望它够了:)
谢谢.
这是我在后端的dropzone init参数和节点S3签名上的作用:
使用Dropzone的HTML前端代码:
var myDropzone = new Dropzone(dropArea, { url:"#", dictDefaultMessage: "Drag n drop or tap here", method: "PUT", uploadMultiple: false, paramName: "file", maxFiles: 10, thumbnailWidth: 80, thumbnailHeight: 80, parallelUploads: 20, autoProcessQueue: true, previewTemplate: dropPreviewTemplate, //autoQueue: false, // Make sure the files aren't queued until manually added previewsContainer: dropPreviewContainer, // Define the container to display the previews clickable: true, //".fileinput-button" // Define the element that should be used as click trigger to select files. accept: function(file, cb) { //override the file name, to use the s3 signature //console.log(file); var params = { fileName: file.name, fileType: file.type, }; //path to S3 signature $.getJSON('/uploader', params).done(function(data) { //console.log(data); if (!data.signedRequest) { return cb('Failed to receive an upload url'); } file.signedRequest = data.signedRequest; file.finalURL = data.downloadURL; cb(); }).fail(function() { return cb('Failed to receive an upload url'); }); }, sending: function(file, xhr) { console.log('sending') var _send = xhr.send; xhr.setRequestHeader('x-amz-acl', 'public-read'); xhr.send = function() { _send.call(xhr, file); } }, processing:function(file){ this.options.url = file.signedRequest; } });
这是我在node.js端使用的库
var Crypto = require("crypto"), AWS = require("aws-sdk"),
这是S3上CORS配置的示例
* PUT *
这是在node.js上生成S3签名的代码:
getPolicy:function(req,res) { var fileId = Crypto.randomBytes(20).toString('hex').toUpperCase(); var prefix = "bl_"; var newFileName = prefix+fileId;//req.query.fileName; var s3 = new AWS.S3(); var s3_params = { Bucket: BUCKET, Key: newFileName, Expires: 60, ContentType: req.query.fileType, ACL: 'public-read' }; s3.getSignedUrl('putObject', s3_params, function(err, data){ if(err){ console.log(err); } else{ var return_data = { signedRequest: data, uploadURL: 'https://'+BUCKET+'.s3.amazonaws.com/'+newFileName, downloadURL: 'http://'+BUCKET+'.s3-website-us-east-1.amazonaws.com/'+newFileName, }; res.write(JSON.stringify(return_data)); res.end(); } }); }
希望其中一些有用.