Google App Engine:在html模板中包含图像blob

时间:2012-11-08 14:01:58

标签: python google-app-engine

我在html模板中显示图像时遇到问题。我设法将图像存储到数据存储区中。但是,我不知道如何将其发送到html文件(或使用URL来显示图像?)。请帮助,非常感谢。以下是我的代码:

main.py

    # -*- coding: utf-8 -*-
    #!/usr/bin/env python2.7

    import webapp2
    import common
    from google.appengine.ext import db

    class Image(db.Model):
        filename = db.StringProperty(required=True)
        data = db.BlobProperty(required=True)
        mimetype = db.StringProperty(required=True)

    class Test(webapp2.RequestHandler):
        def get(self):
            common.render(self, 'test.html', {})

        def post(self):
            imgfile = self.request.POST['image']
            img = Image(filename=imgfile.filename, data=imgfile.value, mimetype=imgfile.type)
            img.put()
            common.render(self, 'test.html', {'imgkey': img.key().id()})

    app = webapp2.WSGIApplication([
        ("/.*", Test)],
        debug=True)

的test.html:

    <htm>
    <head>
    <title>Test</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    <p></p>Upload image: </p>
    <form method="post" action="/test" enctype="multipart/form-data">
    <input type="file" name="image" /><br />
    <input type="submit" name="確定" />
    </form>
    {% if imgkey %}
      Display:<br />
      <img src="http://.../disp?key={{imgkey}}" /><br />
    {% endif %}
    </body>
    </html>

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

class ImageHandler(webapp2.RequestHandler):
    def get(self, image_id):
        image = Image.get(image_id)
        self.response.headers['Content-Type'] = 'image/jpeg'
        self.response.out.write(image.data)

然后在您的映射中,您应该创建一个用于图像处理的URL,例如:

(r'/images/(.*)', ImageHandler)

在HTML代码中,您需要按如下方式创建图片代码:

<img src="/images/{{img1.key}}" /><br />
<img src="/images/{{img2.key}}" /><br />