Created
June 25, 2013 04:30
-
-
Save jrthib/5855940 to your computer and use it in GitHub Desktop.
NodeJS Photo Upload with Azure Storage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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