使用 Gridfs 将 base64 字符串图像存储到 MongoDB

Store base64 string image to MongoDB using Gridfs

我目前正在尝试使用 GridFS 以 base64 字符串的形式将图像存储到 MongoDB,这是我目前的工作解决方案:

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')

请问有没有什么办法可以直接上传图片,而不是将图片另存为文件,然后再读取Gridfs上传? (Google App Engine 不允许文件存储)

我查看了 Gridfs 的 put 函数的文档,但不清楚它所采用的数据类型的确切类型。

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

如何将 base64 字符串转换为 gridfs 支持的字节?

Gridfs put 方法接受二进制文件。

# 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)