MongoDB GridFs with C#, how to store files such as images?

EKet picture EKet · Feb 14, 2011 · Viewed 56.9k times · Source

I'm developing a web app with mongodb as my back-end. I'd like to have users upload pictures to their profiles like a linked-in profile pic. I'm using an aspx page with MVC2 and I read that GridFs library is used to store large file types as binaries. I've looked everywhere for clues as how this is done, but mongodb doesn't have any documentation for C# api or GridFs C#. I'm baffled and confused, could really use another set of brains.

Anyone one know how to actually implement a file upload controller that stores an image uploaded by a user into a mongodb collection? Thanks a million!

I've tried variations of this to no avail.

Database db = mongo.getDB("Blog");
GridFile file = new GridFile(db);
file.Create("image.jpg");

var images = db.GetCollection("images");
images.Insert(file.ToDocument());

Answer

Andrew Orsich picture Andrew Orsich · Feb 14, 2011

Following example show how to save file and read back from gridfs(using official mongodb driver):

 var server = MongoServer.Create("mongodb://localhost:27020");
 var database = server.GetDatabase("tesdb");

 var fileName = "D:\\Untitled.png";
 var newFileName = "D:\\new_Untitled.png";
 using (var fs = new FileStream(fileName, FileMode.Open))
 {
    var gridFsInfo = database.GridFS.Upload(fs, fileName);
    var fileId = gridFsInfo.Id;

    ObjectId oid= new ObjectId(fileId);
    var file = database.GridFS.FindOne(Query.EQ("_id", oid));

    using (var stream = file.OpenRead())
    {
       var bytes = new byte[stream.Length];
       stream.Read(bytes, 0, (int)stream.Length);
       using(var newFs = new FileStream(newFileName, FileMode.Create))
       {
         newFs.Write(bytes, 0, bytes.Length);
       } 
    }
 }

Results:

File:

File im mongodb

Chunks collection:

Chunks collection

Hope this help.