python中,支持通过GridFS使用MongoDB数据库提供的大文件存储功能,本文中通过这种方法将各种格式文件以二进制格式(测试了.pdf、.py格式文件)存入GridFS集合中。
#-*-coding:utf-8-*-import osimport sysfrom gridfs import *from pymongo import MongoClientfrom datetime import datetimepath = sys.path[0] + os.sep # 获取当前文件所在文件夹目录client = MongoClient('127.0.0.1', 27017) # 连接MongoDB数据库db = client.file # 选定数据库,设定数据库名称为filefs = GridFS(db, collection='pdf') # 连接GridFS集合,名称为pdfdef upload(): # 上传文件到GridFS集合中 for filename in os.listdir(path): # 遍历文件 dic = dict() dic['文件名'] = filename dic['上传时间'] = datetime.now() content = open(path + filename, 'rb').read() # 二进制格式读取文件内容 fs.put(content, **dic) # 上传文件def download(): # 下载文件 for cursor in fs.find(): filename = cursor.文件名 content = cursor.read() with open(path + 'temp/' + filename, 'wb') as f: f.write(content)if __name__ == '__main__': # upload() download()
联系客服