保存和读取文件到GridFS

时间:2019-02-19 09:47:53

标签: mongodb pymongo

我对MongoDB和Pyhton相当陌生,但是我对以下问题有疑问。

我想将一些数据文件存储到gridfs中,然后再读取保存的文件。插入接缝很容易,导致我得到一个Objectid并在数据库中“看到”文件。

#Insert external File into DB
def dbInsertFile():
    db = MongoClient().TestDB
    fs = gridfs.GridFS(db)
    fileID = fs.put(open(r'../2_134_1_2_134_022_RTP05.mat_final.csv', 'rb'))
    print(fileID)

给出一个ObjectId:5c6bcc8562b3d50742110562

我来到要获取具有文件ID的文件的那一行

def dbReadFile(fileID):
    db = MongoClient().TestDB
    fs = gridfs.GridFS(db)
    file = fs.get(fileID)
    print(file)

我收到消息:

gridfs.errors.NoFile: no file in gridfs collection Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'TestDB'), 'fs.files') with _id '5c6bcc8562b3d50742110562'

我错过了一些实际将文件存储在数据库中的事情吗?

希望有人可以帮助我:-)

btw ...我在mongo文档中哪里可以找到可以用于put函数的** kwargs?

大事记 亚历克斯

1 个答案:

答案 0 :(得分:0)

# GridOut instance is required for downloading the image locally.
# use get_last_version method call if you are retrieving the image by its 
# filename.
gout = self.fs.get_last_version('required filename')
# Write the data locally. Open a file in write mode.
fout = open('filename of ur choice', 'wb')
fout.write(gout.read())
fout.close()
gout.close()