【问题标题】:Store a PDF file in my MongoDB database with PYmongo error使用 PYmongo 错误在我的 MongoDB 数据库中存储 PDF 文件
【发布时间】:2019-09-30 10:26:48
【问题描述】:

我想使用 PYMonbgo 和 gridfs 在我的 MongoDB 数据库(在 Ubuntu 中)中存储一个 PDF 文件。 但我收到错误 'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte

如何在 MongoDB 中使用 python 存储和接收 PDF?

from pymongo import MongoClient
import gridfs

db = MongoClient('mongodb://localhost:27017/').myDB
fs = gridfs.GridFS( db )
fileID = fs.put( open(('Test.pdf')  ))
out = fs.get(fileID)

【问题讨论】:

    标签: python mongodb pymongo gridfs


    【解决方案1】:

    您需要在阅读后对 PDF 进行适当的编码。我不会假装了解细节。但我已经让它工作了。试试这个,看看它是否也适合你。 (仅供参考,可能还想指定集合)

    import base64
    import gridfs
    
    def write_new_pdf(path):
        db = MongoClient('mongodb://localhost:27017/').myDB
        fs = gridfs.GridFS(db)
        # Note, open with the "rb" flag for "read bytes"
        with open(path, "rb") as f:
            encoded_string = base64.b64encode(f.read())
        with fs.new_file(
            chunkSize=800000,
            filename=path) as fp:
            fp.write(encoded_string)
    

    更新:如何回读 pdf

    def read_pdf(filename):
        # Usual setup
        db = MongoClient('mongodb://localhost:27017/').myDB
        fs = gridfs.GridFS(db)
        # Standard query to Mongo
        data = fs.find_one(filter=dict(filename=filename))
        with open(filename, "wb") as f:
            f.write(base64.b64decode(data.read()))
    

    【讨论】:

    • 你知道如何通过将文件名“Test.pdf”传递给函数来从我的“myDB”集合中接收这个“Test.pdf”吗?
    • 我认为这会奏效。如果没有就大声喊叫。 atm 有点忙,但可以稍后再看。
    • 如果我需要从提取的 PDF 中提取文本而不是保存在我的 PC 中,我该怎么办?
    猜你喜欢
    • 2012-03-30
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 2012-05-06
    • 2021-06-07
    相关资源
    最近更新 更多