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



我目前正在尝试使用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上传?(谷歌应用程序引擎不允许文件存储(

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

"数据可以是str(python 3中的字节(的实例,也可以是提供read((方法的类似文件的对象。">

如何将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)

最新更新