Question

When I use get_last_version to get an image from the database, what is actually returned ie an array, the merged binary data of all the chunks that make up the file (as a string), or something else?

dbname = 'grid_files'
db = connection[dbname]
fs = gridfs.GridFS(db)
filename = "my_image.jpg"
my_image_file = fs.get_last_version(filename=filename)

I'm wanting to base64 encode my_image_file with:

import base64

encoded_img_file = base64.b64encode(my_image_file)
return encoded_img_file

But I'm getting a 500 error.

I haven't been able to glean what is actually returned when using get_last_version from the docs:

http://api.mongodb.org/python/current/api/gridfs/#gridfs.GridFS.get_last_version

More Research:

I followed the logic from this post:

http://blog.pythonisito.com/2012/05/gridfs-mongodb-filesystem.html

And in shell running Python on server could see that Binary() was returned - so should I be able to base64 encode this as demonstrated above?:

>>> import pymongo
>>> import gridfs
>>> import os
>>> hostname = os.environ['OPENSHIFT_MONGODB_DB_URL']
>>> conn = pymongo.MongoClient(host=hostname)
>>> db = conn.grid_files
>>> fs = gridfs.GridFS(db)
>>> list(db.fs.chunks.find())

[{u'files_id': ObjectId('52db4d9e70914413718f2ec4'), u'_id': ObjectId('52db4d9e7
0914413718f2ec5'), u'data': Binary('lots of binary code', 0), u'n': 0}]
Was it helpful?

Solution

Unless there is a better answer, this is what I've come up with.

get_last_version returns a Binary() object.

In regards to base64 encoding it, and returning it, this is how I did it:

dbname = 'grid_files'
db = connection[dbname]
fs = gridfs.GridFS(db)
filename = "my_image.jpg"
my_image_file = fs.get_last_version(filename=filename)
encoded_img_file = base64.b64encode(my_image_file.read())
return encoded_img_file

Then accessed it on the front end with:

$("#my_img").attr("src", "data:image/png;base64," + data);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top