I recently opened another thread on how to store an image in a mongodb database using node.js/mongoose. (Saving image with mongoose)
I kinda got it working, but I'm pretty sure that my current way is not the way to go. This may also be why I'm having trouble showing the stored images back on the frontend.
I have 2 questions:
GridFS
with angular/node/mongoose?Here's my code for saving the image into my database:
var split = req.body.data.image.dataURL.split('base64,');
// ... split until I get 'image/png' and the binary of my image
var avatar = {
data: data,
contentType: type
};
models.UserImages.create({ avatar: avatar, /* ... */})
and my Angular Ctrl for loading the image:
User.findAvatarByUser(data).success(function (data) {
$scope.avatar = data[0].avatar.data;
});
this shows the logging in chrome incl. the error I get:
Any help would be much appreciated!
edit: after lostPixels tip I tried saving the image to the FS. After a little bit of trouble I finally got it working. For the moment I'll save the images to my FS until I know how I really want to handle this problem.
if anyone has the same problem, here's how I save my image on the backend (I found it somewhere on stackoverflow, but unfortunately I lost the link to give credit to the right person, sry for that ;) )
fs.writeFile(newImageLocation, data, 'base64', function (err) {
if (err) throw err
console.log('File saved.')
});
Try to do this:
Saving the image in Node
ImageController.create({image: new Buffer(req.body.image, "base64")},
function(err, img) {
if(err) { return handleError(res, err); }
return res.status(201).json(img);
}
);
Loading and decode in Node
ImageController.findById(req.params.id, function (err, img) {
if(err) { return handleError(res, err); }
if(!foto) { return res.send(404); }
return res.json(img.toString('base64'));
});
Angular Contoller
$http.get('/api/images/'+$scope.image._id).
then(function (response) {
$scope.imgSrc = response.data;
}, function (response) {
});
Angular view
<img ng-src="data:image/jpg;base64,{{imgSrc}}">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With