How to save uploaded images to a MongoDB collection, and retrieve it

lotus_misser picture lotus_misser · Sep 24, 2011 · Viewed 14.2k times · Source

I want to save uploaded files such as a user's avatar image to user collection in MongoDB, I guess the steps are:

  1. user upload a image;
  2. use a FileHandler (IHttpHandler, Asp.net) to accept the file stream in web server;
  3. then I get that file binary and set it to a User class object
  4. finally save the object, so the user collection will get the file binary data.

Am I right about this? Could you give me any clue?

Answer

Bryan Migliorisi picture Bryan Migliorisi · Dec 20, 2011

You should just use GridFS to do it - there is no reason why you should worry about files being too large or too small for it to make sense. GridFS was designed to store files so you should use it.

You could always store a reference to the GridFS file in a normal MongoDB document if you need to, and then load it out of GridFS when you need to use it.

See this thread: MongoDB GridFs with C#, how to store files such as images?