2016-10-13 2 views
0

파일을 MongoDB에 업로드해야합니다. 현재 Flask를 사용하여 현재 파일 시스템의 폴더에 파일을 저장하고 있습니다. GridFS를 사용하지 않고 MongoDB에 파일을 업로드 할 수있는 방법이 있습니까? 나는 오래 전에 이런 일을했다고 믿는다. 그러나 MongoDB를 사용한 이후로 오랫동안 회상 할 수는 없다.MongoDB에 파일 업로드 (크기 <16MB)

내가 업로드하도록 선택한 파일의 크기는 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" }) 
+0

당신이 문서에 BLOB로 저장 시도? – Sammaye

답변

1

몽고 BSON (https://docs.mongodb.com/manual/reference/bson-types/)는 이진 데이터 (binData) 필드 형태를 가진다.
파이썬 드라이버 (http://api.mongodb.com/python/current/api/bson/binary.html)가 지원합니다.

파일을 바이트 배열로 저장할 수 있습니다.

당신의 코드를 약간 수정해야합니다

  1. 추가 수입 : 바이너리를 사용 from bson.binary import Binary
  2. 인코딩 파일 바이트 : 삽입 문에서 encoded = Binary(f, 0)
  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, "r") as fin: 
     f = fin.read() 
     encoded = Binary(f, 0) 

    coll.insert({"filename": file_used, "file": encoded, "description": "test" }) 
+0

binData 형식을 사용하여 파일을 업로드 할 수 없습니다. 내가 binData를 사용하여 파일을 변환하는 오른쪽 트랙에 있는지 확실하지 않습니다. 이 코드의 문제점을 알려주십시오. –

+0

그리고 시간 내 주셔서 감사합니다. 감사합니다. @mike –

+0

대단히 감사합니다. 그것은 매력처럼 작동했습니다. 하나의 작은 수정 비록. 나는 "rb"모드에서 파일을 열어야했다. –