Search code examples
javascriptnode.jsmongodbmongoosegridfs-stream

Display images from GridFs (MongoDB)


I am using the following code to read the image file saved in MongoDB using GridFs:

app.get('/picture', function(req, res) {

 var readstream = gfs.createReadStream({
    filename: 'trooper.jpeg'
 });

 readstream.on('data', function (data) {
  // We got a buffer of data...

 var buf2 = new Buffer(data).toString('base64'); 
 res.send(buf2.toString())
 console.log(buf2.toString());
 console.log(data);
});
  readstream.on('end', function () {
// File finished reading...
});

});

The output of console.log(buff.toString()); is:

dHJvb3Blci5qcGVn

The output of console.log(data); is:

<Buffer 74 72 6f 6f 70 65 72 2e 6a 70 65 67>

To display the image I did this:

<img src="data:image/jpeg;base64,dHJvb3Blci5qcGVn">

I am unable to read and display the image in html from GridFs MongoDB

UPDATE:

I have tried this:

app.get('/picture', function(req, res) {
res.contentType('image/jpeg');
var readstream = gfs.createReadStream('trooper.jpeg');
readstream.pipe(res);

});

The output of the above is:

enter image description here


Solution

  • Unless you really need to embed images into page, use pipes as of saintedlama's answer.

    dHJvb3Blci5qcGVn is base64 encoded string "trooper.jpeg". Please ensure you correctly saved binary data to GridFS at the first instance.

    You can query it directly and check content of the file stored in the db.