Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 509
lotus_misser Avatar asked Sep 24 '11 11:09

lotus_misser


People also ask

Can you save images in MongoDB?

There are three ways to store the images in MongoDB: GridFS, Within Document, and Referencing an external URL. If an image or any binary file which is of size less than 16MB can be stored in MongoDB using Binarydata ( bindata ) type.

How do I store images in MongoDB schema?

So for storing an image in MongoDB, we need to create a schema with mongoose. For that create the file `model. js` file and define the schema. The important point here is that our data type for the image is a Buffer which allows us to store our image as data in the form of arrays.

Can MongoDB support the storage and retrieval of image and video?

Large objects, or "files", are easily stored in MongoDB. It is no problem to store 100MB videos in the database. This has a number of advantages over files stored in a file system. Unlike a file system, the database will have no problem dealing with millions of objects.


2 Answers

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?

like image 118
Bryan Migliorisi Avatar answered Sep 28 '22 07:09

Bryan Migliorisi


According to Mongo grid fs documentation. If your files are all smaller than the 16 MB BSON Document Size limit, consider storing each file in a single document instead of using GridFS. You may use the BinData data type to store the binary data. See your drivers documentation for details on using BinData.

like image 44
Christopher Doty Avatar answered Sep 28 '22 08:09

Christopher Doty