Retrieving and displaying image from GridFS Python Flask Mongodb

Hi I am currently using Python Flask to store my images, I have successfully use gridfs to store the images into the mongodb, but now I am unsure how to retrieve the images.

I understand that since the files are large it will be split into chunks in the fs.chunks. I am able to query the results as I have created an id for all my images and attach it to the fs.files and I will just use the objectID to query my fs.chunks collections. Howeve after that I am not sure how to display the images.

Does anyone know how to retrieve images from gridfs in mongodb for python flask.


Hi so I found a way to get the images from mongodb using python flask.

This was how we configured mongodb connection

app = Flask(__name__)
mongo = os.getenv('MONGODB')
client = MongoClient(mongo)
db = client.products_db
products = db.products
grid_fs = gridfs.GridFS(db)

So for the first code block, this is how I saved the image on the gridFS using this code. I believe that using grid_fs.put will return an id and that will allow you to call it from the other fs.chunks and fs.files

@app.route('/image/', methods = ["POST"])
def saveImage():
if 'image' in request.files:
    image = request.files['image']
    name = request.form.get('name')
    id = grid_fs.put(image, content_type = pimage.content_type, filename = name)
query = {
    'id':id,
    'name': request.form.get('name'),
    'desc':request.form.get('desc'),
}
status = products.insert_one(query)
if status:
    return jsonify({'result': 'Image uploaded successfully'}),201
return jsonify({'result': 'Error occurred during uploading'}),500

To retrieve the image from the grid_fs. I had to use pip install codecs to use codecs

item = products.find_one({'id': id})
image = grid_fs.get(item['id'])
base64_data = codecs.encode(image.read(), 'base64')
image = base64_data.decode('utf-8')

It can then be displayed on html using, the image within the html is the binary string received from the grid_fs

<img src = "data:image/png;base64, {{image}}" alt= "myImage"/>

Late edit: Hi anyways, the proper way to store images would be to store the image in a object storage service such as AWS S3 or Google Cloud Storage, and store the link of that image in your DB, storing the image itself into the DB is bad practice