RonZhang724
RonZhang724

Reputation: 575

Store base64 string image to MongoDB using Gridfs

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?

Upvotes: 1

Views: 3155

Answers (1)

Methkal Khalawi
Methkal Khalawi

Reputation: 2477

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)

Upvotes: 1

Related Questions