简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM