0

I am using GridFS to retrive image from mongoDB:

I do:

    // Connect to the db
    MongoClient.connect("mongodb://10.8.2.232/mydb", function(err, db) {
      if(err) return console.dir(err);
                var fileId = mongoose.Types.ObjectId("542e684a8a1cec178a172671");
                var gridStore = new GridStore(db, fileId, 'r');

                gridStore.open(function (err, gridStore) {
                    //console.log(gridStore.currentChunk.data.buffer);
                    gridStore.read(function (error,data){
                        console.log(data, 'binary');
                        res.writeHead(200, {'Content-Type': 'image/png'});
                        var s = gridStore.stream(true);
                        console.log(s);
                    });
                });
    });
    }).listen(8124, "127.0.0.1");

console.log('Server running at http://127.0.0.1:8124/');

Connexion to MongoDB OK "S" displays a JSON with some information about the image:

currentChunk:
  { file: [Circular],
    writeConcern: [Object],
    objectId: 542e65378a1cec1227ae2bb1,
    chunkNumber: 0,
    data: [Object],
    internalPosition: 17959 } },

But I want to display the image:

fs.chunks:

{
        "_id" : ObjectId("542e684a8a1cec1745zs3"),
        "n" : 1,
        "data" : BinData(0,"2N6DSSfbCN/LLacNDYrJUQDEZgimMUwFpQGoJP0RU19Bi4PM82DjrUnKhE/P9v7P8ZveD1oDpFBM0iml9NE3WQmAvYFoG+nhD73Jm4N9b4LpylaAN5Ef+gVdgGSTAfSUwOikXoVick5pSQCkRmTCU5NT9VVfjHdAx74/ZhFRj+TIRjzlAhzkACBElzgMwGCo7tX+FYrpQLJ5KRmXiwF"),
        "files_id" : ObjectId("542e684a8a1cec178a172671")
}

How I can be able to retrieve my image (in data) in the browser?

Thanks!

Carlos
  • 79
  • 1
  • 4
  • 16
  • [Node.js displaying images from Mongo's GridFS](http://stackoverflow.com/questions/10588872/node-js-displaying-images-from-mongos-gridfs), this might help! – Ravi Oct 12 '14 at 15:58

1 Answers1

1

Don't use read() if you are going to stream the file. Example:

gridStore.open(function (err, gridStore) {
  if (err) {
    res.writeHead(500);
    return res.end();
  }
  res.writeHead(200, {'Content-Type': 'image/png'});
  gridStore.stream(true).on('end', function() {
    db.close();
  }).pipe(res);
});
mscdex
  • 104,356
  • 15
  • 192
  • 153