图片编码为Base64存入MongoDB时字符串不一致问题求助
问题
尝试使用Python将图片编码为Base64后上传至MongoDB,存入数据库的字符串与预期不符。将编码后的enc_file输出到文本文件,该文件中的Base64字符串可正常转回图片,但MongoDB中显示的内容异常。
代码示例
import os import base64 import pymongo def checkImage(file_name): if file_name.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')): return True return False def checkFile(file_name): if(os.path.exists(file_name)): return True return False def convert64(file_name): image_file = open(file_name, "rb") bs64_str = base64.b64encode(image_file.read()) return bs64_str conn_str = "--" connection = pymongo.MongoClient(conn_str, serverSelectionTimeoutMS=5000) db = connection.test file_meta = db.file_meta def main(): while(True): file_name = input("Enter the image name to upload: ") # check if the file exists or not in our folder if checkFile(file_name): # verify that the file is an image file if checkImage(file_name): # print(convert64(file_name)) enc_file = convert64(file_name) coll = db.testcollection with open('base64.txt', 'wb') as f: f.write(enc_file) coll.insert_one({"filename": file_name, "file": enc_file, "description": "test"}) break; else: print("Please enter a valid image file") main()
原因
base64.b64encode()返回的是bytes类型数据,直接传入MongoDB时,pymongo会自动将其识别为二进制数据(BinData类型)存储,因此在MongoDB中看到的是二进制封装格式,而非明文Base64字符串。而写入本地文件时,用wb模式直接写入bytes,文件中会保存对应的ASCII明文,所以两者表现不同。
解决方案
将Base64的bytes结果解码为字符串后再存入MongoDB,修改convert64函数即可:
def convert64(file_name): with open(file_name, "rb") as image_file: # 改用with语句自动关闭文件,更安全 bs64_bytes = base64.b64encode(image_file.read()) return bs64_bytes.decode('utf-8') # 解码为utf-8字符串
若要让本地文件内容与数据库存储的完全一致,写入文件时也可改用w模式写入字符串:
with open('base64.txt', 'w', encoding='utf-8') as f: f.write(enc_file)
这样存入MongoDB的file字段就会和本地文本文件中的Base64字符串完全一致。
内容的提问来源于stack exchange,提问作者Kyle Hrivnak
相关产品推荐
相关产品推荐

