Mongoengine: How to use filefield for storing images and files



If you want to store files in mongodb you should use the GridFS since mongodb has file size limitations. MongoEngine is an Object-Document Mapper for Python. It provides support to store files using FileField and it uses GridFS. The file field beheaves like a python file object.

With the field field you can: * Write * Read * Delete * Replace

FileField is like a document that will be stored in one file on the GridFS. You can write the content only once, if you want to overwrite you will need to delete the file and create a new one. The FileField is similar to the file object, however it has some differences like you can only use one time the file for writetting.

How to use the FieldField.

You need to defined a FileField attribute in you model:

from mongoengine import Document
from mongoengine import FileField

class Article(Document):
    # by default collection_name is 'fs'
    # you can use collection_name parameter to set the name of the collection
    # use collection_name like this: FileField(collection_name='images')
    upload = FileField()

art = Article()
with open('image.png', 'rb') as image_file:
    art.upload.put(image_file, content_type='image/png')

# If you are using FileField in a http framework you will need StringIO
# as a replacement for the object file or you can use TemporaryFile
mem_file = StringIO()
art.upload.put(mem_file, content_type='image/png')

# if you want to replace the content of a file

with open('image.png', 'rb') as image_file:
    art.upload.replace(image_file, content_type='image/png')

FileField methods

  • get
  • new_file
  • put
  • replace
  • write
  • writelines
  • close
  • replace

To write content you can use put method, it supports the optional parameter content_type. For reading use read. You can use replace to owerwrite the contents of the file or use delete to delete the file. You can also use write, but you will need to use close when you finish to write the contents. If you want to create a new file you can use new_file

Mongoengine Document with multiple Files

YOu can store multiple images in on Mongoengine document using the list field, here is an example:

from mongoengine import Document
from mongoengine import FileField, EmbeddedDocument, EmbeddedDocumentField

class ArticleImage(EmbeddedDocument):
    image = FileField()

class Article(Document):
    images = ListField(EmbeddedDocumentField(ArticleImage))

art = Article()
image_1 = ArticleImage()
with open('image1.png', 'rb') as image_file:
    image_1.put(image_file, content_type='image/png')
image_2 = ArticleImage()
with open('image2.png', 'rb') as image_file:
    image_2.put(image_file, content_type='image/png')