【发布时间】:2021-03-22 15:06:37
【问题描述】:
我正在做一个项目,我想在 Mongo 集合中存储 PDF 数据。我意识到社区中已经有人问过这个问题,但我正在为结果而苦苦挣扎。我的代码能够将一个文档插入到集合中,但是因为它进入了一个空白的二进制对象而停止了。
import base64, os
import pymongo
import bson
from pathlib import Path
file_used = 'sample.pdf'
my_file = Path(file_used)
if my_file.is_file():
print("File Exists") #prints successfully
with open(file_used, 'rb') as fout:
string = base64.b64encode(fout.read())
collection.insert_one({"filename":file_used,"pdf_data":string})
MDB Compass 中的文档:
{
"_id":{"$oid":"60583bfdffea362641c50944"},
"filename":"sample.pdf",
"pdf_data":{"$binary":"","$type":"0"}
}
我的 python 文件也与我的示例 PDF 文件位于同一目录中。
执行:python3 test.py
如何进一步调试我的代码?提前感谢您的帮助?
【问题讨论】:
-
语句
collection.insert_one({ ...中的变量collection的值是多少? -
@prasad_ 是 db.coll。该文档已成功发布到 Mongo。问题在于 PDF 文件。
标签: python mongodb binary pymongo