Alan Yudhahutama
Alan Yudhahutama

Reputation: 53

How to retrieve image file from Mongo using Sails.JS + GridFS?

I'm currently building web using Sails.js and got stuck in retrieving image file from GridFS. I have successfully uploading the file using skipper-gridfs to my mongo gridfs. I have no idea to display the file in the correct way (I'm new in Sails.js and Node system)

Here is my code for retrieving image file from gridfs looks like in FileController.js (I'm using gridfs-stream):

show: function  (req, res, next) {
    var mongo = require('mongodb');
    var Grid = require('gridfs-stream');
    var buffer="";

    // create or use an existing mongodb-native db instance
    var db = new mongo.Db('testDb', new mongo.Server("192.168.0.2", 27017), {safe:true});
    var gfs = Grid(db, mongo);

    // streaming from gridfs
    var readstream = gfs.createReadStream({
      filename: 'e1ecfb02-e095-4e2f.png'
    });

    //check if file exist
    gfs.exist({
      filename: 'e1ecfb02-e095-4e2f.png'
    }, function (err, found) {
      if (err) return handleError(err);
      found ? console.log('File exists') : console.log('File does not exist');
    });

    //buffer data
    readstream.on("data", function (chunk) {
        buffer += chunk;
        console.log("adsf", chunk);
    });

    // dump contents to console when complete
    readstream.on("end", function () {
        console.log("contents of file:\n\n", buffer);
    });     
}

When I ran it, the console showed nothing. There is no error either.

How should I fix this?

Additional Question:

  1. Is it better & easier to store/read file to/from local disk instead of using gridfs?
  2. Am I correct in choosing gridfs-stream to retrieve the file form gridfs?

Upvotes: 3

Views: 2589

Answers (2)

ayon
ayon

Reputation: 2180

In the skipper-gridfs codes and there's a 'read' method that accept fd value and returns the required file corresponding to that value. So, you just have to pull that file from mongo by that method and send as a response. It should work file.

download: function (req, res) {
    var blobAdapter = require('skipper-gridfs')({
        uri: 'mongodb://localhost:27017/mydbname.images'
    });

    var fd = req.param('fd'); // value of fd comes here from get request
    blobAdapter.read(fd, function(error , file) {
        if(error) {
            res.json(error);
        } else {
            res.contentType('image/png');
            res.send(new Buffer(file));
        }
    });
}

I hope it helps :)

Additional Questions:

  1. Yes, using gridfs is better both in performance and efficiency. And normally mongodb has a limitation of 16MB probably for binary files, but using gridfs you can store any size file, it breaks them in chunks and stores them.

  2. Retrieving has been shown above.

Upvotes: 2

r0hitsharma
r0hitsharma

Reputation: 1762

You can now use skipper-gridfs in sails to manage uploads/downloads.

var blobAdapter = require('skipper-gridfs')({uri: 'mongodb://jimmy@[email protected]:27017/coolapp.avatar_uploads' });

Upload:

req.file('avatar')
.upload(blobAdapter().receive(), function whenDone(err, uploadedFiles) {
  if (err) return res.negotiate(err);
  else return res.ok({
    files: uploadedFiles,
    textParams: req.params.all()
  });
});

Download

blobAdapter.read(filename, callback);

Bear in mind the file name will change once you upload it to mongo, you have to use the file name returned in the first response.

Upvotes: 0

Related Questions