1

I am currently trying to store an image in the form of base64 string to the MongoDB using GridFS, here is my working solution so far:

def upload(image_string):
    image_data = base64.b64decode(image_string)
    image = Image.open(io.BytesIO(image_data))
    image.save("foo.jpeg")
    with open("foo.jpeg", "rb") as img:
        storage = GridFS(mongo.mydb, "fs")
        storage.put(img, content_type='image/jpeg')

I was wondering if there is a way to directly upload the image instead of saving the image as a file and read it again for the Gridfs to upload? (Google App Engine doesn't allow file storage)

I looked at the documentation of the put function of Gridfs, but it is quite unclear on the exact type of data type it is taking.

"data can be either an instance of str (bytes in python 3) or a file-like object providing a read() method."

How do I convert the base64 string to bytes that gridfs supports?

1 Answer 1

1

Gridfs put method accepts binaries.

# encode your image to binary text
with open("unnamed.jpg", "rb") as image:
    # read the image as text and convert it to binary
    image_string = base64.b64encode(image.read())


# create Gridfs instance
fs = gridfs.GridFS(db)

# add the image to your database
put_image = fs.put(image_string)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, but my input here is a base64 string already and when I try to upload the string directly using the put function, I only pushed the string to the server. storage = GridFS(mongo.ourcloset2, "fs") image_id = storage.put(image_string, encoding='utf-8') The image is not stored as an image object for some reason.
can you please explain what do you mean by not stored as an image object?. Images using Gridfs will be saved in Mongodb as binary string, then to use them, you can retrieve them and convert them again to images.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.