Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying Images in Angular.js from MongoDB

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:

  1. How can I display the image with my current configuration
  2. Since my code is clearly wrong at this point I'm still wondering whats the way to go to store images with mongoDB. Am I supposed to only store the URL and save the image on my fileserver? Has anyone a working example on how to use 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:

enter image description here

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.')
    });
like image 292
Markus Avatar asked Dec 08 '14 21:12

Markus


1 Answers

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}}">
like image 186
Martin Pielvitori Avatar answered Oct 20 '22 21:10

Martin Pielvitori