Abdelouahab Pp
Abdelouahab Pp

Reputation: 4450

can't get pictures from gridFS using Tornado

my problem is that i can get the save picture to gridFS even if it's there, i've verified and it show me the piture and its name and the size from the console. here is the code:

conn = Connection()

the classe that saves to the database:

class Profile(tornado.web.RequestHandler):

def post(self):
      self.db = conn["essog"]
      avat = self.request.files['avatar'][0]["body"]
      avctype = self.request.files['avatar'][0]["content_type"]
      nomfich = self.request.files['avatar'][0]["filename"]
      #..operation using PIL to decide to save the picture or not
      self.fs = GridFS(self.db)
      avatar_id = self.fs.put(avat, content_type=avctype, filename=nomfich) #change the   name later to avoid delete using the same name, so generating a different name...
      .....
      user={..., "avatar":avatar_id}
      self.db.users.insert(user)
      self.db.users.save(user)

the class that reads from the database:

class Profil(tornado.web.RequestHandler):

  def get(self):
      self.db = conn["essog"]
      self.fs = GridFS(self.db)
      avatar_id = self.db.users.find_one()["avatar"]
      ...
      avatar = self.fs.get(avatar_id).read()
      self.render("profile.html",..., avatar=avatar)

and in the view (profile.html)

img src="{{avatar}}" />

but nothing is displayed!

Upvotes: 0

Views: 458

Answers (2)

ESV
ESV

Reputation: 7730

The src attribute of an img tag does not (typically) contain the image data itself, but rather the URL of the image. I think you're confusing two separate requests and responses:

  1. HTML page that contains an <img src="..." /> tag:

    class Profil(tornado.web.RequestHandler):
        self.render('profile.html',
            avatar=self.reverse_url('avatar', avatar_id))
    
  2. image itself (which needs a separate handler):

    class Avatar(tornado.web.RequestHandler):
        def get(self, avatar_id):
            avatar = self.fs.get(avatar_id)
            self.set_header('Content-Type', avatar.content_type)
            self.finish(avatar.read())
    

Upvotes: 2

Ross
Ross

Reputation: 18111

Unless you want to use a base64 URI for the source of the image, you should use a url and then create a view for returning the data from that view. If you are using nginx you might be interested in the nginx-gridfs module for better performance.

Upvotes: 3

Related Questions