Reading images from gridfs

I made a nodejs script that inserts images into a database using gridfs-stream.
Now I need to read those image files from Meteor. It seems CollectionFS only reads files that were uploaded.

So, what will I need to read those files from Meteor?

First, you should write your files with an _id and filename in the options.

new Mongo.ObjectID()

Then you should have an on finish event on the writestream, if this triggers you store the _id and filename to a collection.

Now you have a reference to the files by querying the collection. You can simply create readStreams with the _id you want and get the actual files that way.

TL;DR: Create a collection where you store a reference (id or name) to the files you’re writing to gridfs. That way you can simply read them back.

1 Like

I have another collection which has a ‘filename’ field, the same filename that is stored on GridFS.

The thing is: I have no clue on how to create readStreams from GridFS on Meteor and make them available for the client use them templates.

I think a better approach is to store images using CollectionFS insert method inside Meteor rather than doing it externally.

That way I can query, transform, filter, do all nifty things CollectionFS provides. Of course, I will still need to create a reference collection like you said, to store a filename and a fileObj _id.

But thanks for the idea!

It’s right there in the docs for grids-stream

    // streaming from gridfs
var readstream = gfs.createReadStream({
  filename: 'my_file.txt'
});

//error handling, e.g. file does not exist
readstream.on('error', function (err) {
  console.log('An error occurred!', err);
  throw err;
});

readstream.pipe(response);

But yeah, collectionfs works great (using it myself)

2 Likes

Yeah! And it works like a charm.

Bump.

I’m trying to use gridfs-stream but I get an error.

Meteor.methods({
  emailReport: function(to, from, subject, body, imageId) {
    console.log(imageId);

    var doc = ReportImages.findOne({ _id: imageId });
    
    var mongo = Meteor.npmRequire('mongodb');
    var Grid = Meteor.npmRequire('gridfs-stream');
    
    var db = ReportImages.rawDatabase();
    var gfs = Grid(db, mongo);
    
    var readstream = gfs.createReadStream({
      _id: imageId
    });
    
    var response = [];
    
    readstream.pipe(response);
  }
});

I’m not able to supply the raw db from Meteor and get this error
Exception while invoking method ‘emailReport’ TypeError: Object [object Object] has no method ‘rawDatabase’

How did you setup gridfs-stream in your Meteor app?

I apologize in advance, i’m an iOS dev trying to pick up Meteor…

I have used the same code to view image from gridfs but i am getting an error:
TypeError: Cannot read property ‘readPreference’ of null at new GridStore