我需要将文件上传到 MongoDB。目前我正在使用 Flask 将文件保存在当前文件系统的文件夹中。有没有一种方法可以在不使用 GridFS 的情况下将文件上传到 MongoDB?我相信我很久以前做过这样的事情,但我不记得自从我上次使用 MongoDB 以来已经很久了。
我选择上传的任何文件大小不超过 16MB。
更新:我尝试使用 binData
转换图像文件,但它抛出错误 global name binData is not defined
。
import pymongo
import base64
import bson
# establish a connection to the database
connection = pymongo.MongoClient()
#get a handle to the test database
db = connection.test
file_meta = db.file_meta
file_used = "Headshot.jpg"
def main():
coll = db.sample
with open(file_used, "r") as fin:
f = fin.read()
encoded = binData(f)
coll.insert({"filename": file_used, "file": f, "description": "test" })
最佳答案
Mongo BSON ( https://docs.mongodb.com/manual/reference/bson-types/ ) 具有字段的二进制数据 (binData
) 类型。
Python 驱动程序 ( http://api.mongodb.com/python/current/api/bson/binary.html ) 支持它。
您可以将文件存储为字节数组。
你的代码应该稍微修改一下:
- 添加导入:
from bson.binary import Binary
- 使用二进制编码文件字节:
encoded = Binary(f)
- 在插入语句中使用编码值。
完整示例如下:
import pymongo
import base64
import bson
from bson.binary import Binary
# establish a connection to the database
connection = pymongo.MongoClient()
#get a handle to the test database
db = connection.test
file_meta = db.file_meta
file_used = "Headshot.jpg"
def main():
coll = db.sample
with open(file_used, "rb") as f:
encoded = Binary(f.read())
coll.insert({"filename": file_used, "file": encoded, "description": "test" })
关于python - 将文件(大小 <16MB)上传到 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40015103/