簡體   English   中英

使用 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 function 的文檔,但它所采用的數據類型的確切類型尚不清楚。

“數據可以是 str 的實例(python 3 中的字節)或提供 read() 方法的類似文件的 object。”

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM