简体   繁体   English

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

[英]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:我目前正在尝试使用 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')

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?我想知道是否有一种方法可以直接上传图像而不是将图像保存为文件并再次读取以供 Gridfs 上传? (Google App Engine doesn't allow file storage) (Google App Engine 不允许文件存储)

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.我查看了 Gridfs 的put function 的文档,但它所采用的数据类型的确切类型尚不清楚。

"data can be either an instance of str (bytes in python 3) or a file-like object providing a read() method." “数据可以是 str 的实例(python 3 中的字节)或提供 read() 方法的类似文件的 object。”

How do I convert the base64 string to bytes that gridfs supports?如何将 base64 字符串转换为 gridfs 支持的字节?

Gridfs put method accepts binaries. 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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