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

P R*_*aju 2 python file-upload file mongodb

我需要将文件上传到 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" })
Run Code Online (Sandbox Code Playgroud)

Mik*_*neu 7

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" })
Run Code Online (Sandbox Code Playgroud)