python - 将文件(大小 <16MB)上传到 MongoDB

标签 python mongodb file file-upload

我需要将文件上传到 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 ) 支持它。

您可以将文件存储为字节数组。

你的代码应该稍微修改一下:

  1. 添加导入:from bson.binary import Binary
  2. 使用二进制编码文件字节:encoded = Binary(f)
  3. 在插入语句中使用编码值。

完整示例如下:

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/

相关文章:

c# - Azure 表存储多行查询性能

linux - 如何使某些文件对进程可见,以及当某些进程访问它然后提供某些 Internet 流的内容时?

python - 返回类的类型声明在 PyCharm 中给出错误

python +安全

python - 在python中按最小值组合重叠栅格

python - python 中 os.rename 的中断

python - python中的文本文件循环缓冲区

mongodb - 微服务应用程序......数据库的 Docker 卷或没有 Docker 卷?

java - 如何将 Spring MVC 连接到远程 MongoDB,以使用 MongoOperations 接口(interface)?

javascript - 如何使用nodejs获取mongodb的slave状态?