I know there are quite a few threads on this topic already, but unfortunately I didn't find my answer until now. I use angular.js with the example code from http://angular-js.in/image-upload/ to get the image from the client. This part works
Now to the node/mongodb part, here's my backend model:
var userSchema = new mongoose.Schema({
avatar: { data: Buffer, contentType: String },
// ...
});
module.exports = mongoose.model('User', userSchema);
and my node code:
exports.createAvatar = function (req, res) {
var avatar = {
data: req.body.data.image, // see below
contentType: 'image/png'
}
models.DUser
.findById(index.findUserId(req))
.exec(function (err, user) {
user.avatar = avatar;
// ...
user.save(function (err, user) {/* ... */ });
and my angularCtrl:
var foo = {
image: image,
imageName: image.name,
};
$http.post('/api/users', {data: foo })
.success(function (result) { /*...*/ });
Beside from req.body.data.image I tried many different variations like req.body.data.image.dataURL, req.body.data.image.dataURL.data, but nothing worked so far. My Logging of req.body.data.image shows:
{ file:
{ webkitRelativePath: '',
lastModified: 1411073963000,
lastModifiedDate: '2014-09-18T20:59:23.000Z',
name: '3770316278.png',
type: 'image/png',
size: 32493 },
url: 'blob:http%3A//127.0.0.1%3A3000/cb20debc-8a3a-468f-ab5c-39299f7ec52b',
dataURL: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACHCAYAAAC.....
How can I save the image to the database?
edit
I tried to save everything after base64,
from req.body.data.image.dataURL
into the avatar like this:
var split = req.body.data.image.dataURL.split('base64,');
var type = split[0];
var data = split[1];
var avatar = {
data: type,
contentType:'image/png'
};
the save message is still:
user.avatar = avatar
user.save(function (err, user) {}
But I still get the error
TypeError: Cannot set property 'avatar' of null
since my question changed a bit, I'm marking this one as solved, the new question is here: Displaying Images in Angular.js from MongoDB