Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()); 
like image 968
EKet Avatar asked Feb 14 '11 02:02

EKet


People also ask

How does MongoDB store files in GridFS?

It is kind of a file system to store files but its data is stored within MongoDB collections. GridFS has the capability to store files even greater than its document size limit of 16MB. GridFS divides a file into chunks and stores each chunk of data in a separate document, each of maximum size 255k.

How do I create a GridFS bucket in MongoDB?

Create a GridFS Bucketcreate() method to create the GridFSBucket . MongoDatabase myDatabase = mongoClient. getDatabase("mydb"); // Create a gridFSBucket using the default bucket name "fs" GridFSBucket gridFSBucket = GridFSBuckets. create(myDatabase);

Why do we need GridFS in MongoDB?

In MongoDB, use GridFS for storing files larger than 16 MB. In some situations, storing large files may be more efficient in a MongoDB database than on a system-level filesystem. If your filesystem limits the number of files in a directory, you can use GridFS to store as many files as needed.


1 Answers

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.

like image 179
Andrew Orsich Avatar answered Oct 02 '22 12:10

Andrew Orsich