我无法调整代码以允许ajax上传。我可以直接上传到S3工作,但是想使用ajax来显示上传进度。
JS
$('#upload-input').on('change', function(){
var files = $(this).get(0).files;
if (files.length > 0){
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('uploads[]', file, file.name);
}
$.ajax({
type: 'POST',
processData: false,
contentType: false,
data: formData,
url: '/upload',
success : function(data){
getDetail();
console.log('picture uploaded ', data);
},
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').text(percentComplete + '%');
$('.progress-bar').width(percentComplete + '%');
if (percentComplete === 100) {
$('.progress-bar').html('Done');
}
}
}, false);
return xhr;
}
});
}
});
后端
设置变量
var aws = require('aws-sdk');
aws.config.loadFromPath('./data/s3config.json');
var multer = require('multer');
var multerS3 = require('multer-s3');
var s3 = new aws.S3({});
var upload = multer({
storage: multerS3({
s3: s3,
bucket: 'roe.pictures',
acl: 'public-read',
metadata: function (req, file, cb) {
cb(null, {fieldName: file.fieldname});
},
key: function (req, file, cb) {
cb(null, Date.now().toString())
}
})
});
设置通话后
问题是我不知道如何将文件添加到'upload.array'参数中。如果我直接从html表单加载文件,我可以使用输入字段的名称。由于没有'req'对象,我不能使用req.body。我是否必须将其包装到另一个函数中?
谢谢!
app.post('/upload', upload.array(this.body, 3), function(req, res, next) {
var newPics = [];
if(req.files) {
req.files.forEach(function(p) {
newPics.push({key : p.key, originalName : p.originalname, mimeType : p.mimetype, size : p.size})
});
Room.update({_id : req.signedCookies.prop},
{ $push: { pPics : { $each : newPics }}})
.exec(function(err, r) {
if(err) return err;
console.log('Successfully uploaded ' + req.files.length + ' files! with result ' + r);
res.redirect(req.get('referer'));
});
} else {
console.log('nothing to upload');
res.redirect(req.get('referer'));
}
});