I am having trouble adjusting my code to allow ajax uploads. I have the direct upload to S3 working but would like to use ajax to show upload progress.
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;
}
});
}
});
backend
setting up the variables
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())
}
})
});
Setting up post call
The issue is that I don't know how to add the files to the 'upload.array' parameter. If I load the files directly from the html form, I can just use the name of the input field. Since there is no 'req' object, I can't use req.body. Do I have to wrap this into another function?
Thanks!!
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'));
}
});