Skip to content

Instantly share code, notes, and snippets.

@jrthib
Created June 25, 2013 04:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jrthib/5855940 to your computer and use it in GitHub Desktop.
Save jrthib/5855940 to your computer and use it in GitHub Desktop.
NodeJS Photo Upload with Azure Storage
exports.addCarPhoto = function(req, res) {
var userID = req.user._id;
var carsBaseURI = "http://sobrioapp.blob.core.windows.net/cars/";
// setup photo meta data
var type = req.files.photo.type;
var filename = req.params.id + "-" + req.files.photo.name;
var path = req.files.photo.path;
// check if it has the right filetype
if(type == "image/jpeg" || type == "image/jpg" || type == "image/png") {
// initiate a blobService object for Azure
var blobService = azure.createBlobService();
var options = {
contentType: type,
metadata: { fileName: filename }
}
// Fire off in series so that the tmp photo isn't deleted before its fully uploaded
async.series({
block: function(callback) {
blobService.createBlockBlobFromFile('cars', filename, path, options, callback);
},
unlink: function(callback) {
fs.unlink(path, callback);
}
}, function(err, results) {
// Update the user's car with the new photo
var update = User.findOneAndUpdate({
"_id": userID,
"cars._id": req.params.id
}, {
$set: {
'cars.$.photo': carsBaseURI + results.block[0].blob
}
});
var promise = update.exec();
promise.addBack(function(err, user) {
if(err) {
res.send(err);
} else {
res.send(user.cars);
}
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment