Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a file in Mongodb's GridFS with pymongo results in a truncated file - python 2.7 on Windows 7

Saving a file in Mongodb's GridFS with pymongo results in a truncated file.

from pymongo import MongoClient
import gridfs
import os

#just to make sure we aren't crazy, check the filesize on disk:
print os.path.getsize( r'owl.jpg' )

#add the file to GridFS, per the pymongo documentation: http://api.mongodb.org/python/current/examples/gridfs.html
db = MongoClient().myDB
fs = gridfs.GridFS( db )
fileID = fs.put( open( r'owl.jpg', 'r')  )
out = fs.get(fileID)
print out.length

On Windows 7, running this program generates this output:

145047
864

On Ubuntu, running this program generates this (correct) output:

145047
145047

Unfortunately, the application I'm working on is targeting the Windows OS...

Any help would be appreciated!

so you can reproduce my example more rigorously, 'owl.jpg' was downloaded from: http://getintobirds.audubon.org/sites/default/files/photos/wildlife_barn_owl.jpg

like image 504
D. Reagan Avatar asked Dec 12 '13 18:12

D. Reagan


1 Answers

Heh, changing

fileID = fs.put( open( r'owl.jpg', 'r')  )

to:

fileID = fs.put( open( r'owl.jpg', 'rb')  )

Fixes the behavior of the program on Windows 7. Too bad the behavior is different between OS's...

like image 116
D. Reagan Avatar answered Nov 03 '22 20:11

D. Reagan