Display image in my HTML from GridFS

367 views Asked by At

I've checked this post and this post and they don't work. I successfully store an .png image in mongodb using gridfs-locking-stream and also retrieve that picture.

this is how the database look like after executing the db.fs.files.find().pretty() command: database I've written a function called sendFileToView so that I can use it multiple time. The function recieve the id of the picture and return the readStream :

function sendFileToView(id, callback) {
gfs.createReadStream({_id: id},
    function (err, readstream) {
        if (err) callback(err, null);
        else {
            if (readstream) {
                callback(null, readstream);
            }
        }
    });
}

And I'm using this function in my router like this:

PicturesRouter.route('/:picId')

.get(function (req, res, next) {
    console.log(req.params.picId);
    GridFS.sendFileToView(req.params.picId,
        function (err, readStrem) {
            if (err) next(err);
            else if (readStrem) {
                res.writeHead(200, {'Content-Type': 'image/png'});
                readStrem.pipe(res);
            }
        })
});

Now in my client side I have this service. the service has a function that simply return $resource so that I can use it in my controller:

.service('lessonsService', ['$resource', '$http', 'baseURL',
function ($resource, $http, baseURL) {
  this.picturesRes = function () {
    return $resource(baseURL + 'pictures/:id');
  }
}])

And finally this is how I try to show the image in my html page:

lessonsService.picturesRes().get({id: "59a14427884e6a1f58a1e21d"})
    .$promise.then(function (response) {
      console.log('success function');
      console.log(response);
      $scope.imgSource = 'data:image/jpeg;base64,' + btoa(response);
    },
    function (response) {
      console.log("failure function");
      console.log(response);
    });

in HTML:

<img src={{imgSource}} alt="Something">

As you can see I'm printing the response in my console to see what it looks like. This is what I get: console output

The output looks so strange and the problem is that the picture is not displayed in the view. It's been weeks that I'm working on it. Would it be alright if you helped me?

0

There are 0 answers