使用Google App Engine提供图片?

时间:2013-11-03 18:23:47

标签: google-app-engine url get serving

我正在编写一个简单的应用程序,允许用户上传图像,应用程序将直接在上传表单下方显示图像。但是我无法弄清楚如何正确显示图像。我在堆栈溢出中尝试了几个答案。他们似乎都没有回答我的问题。任何人都可以看看我的代码,看看我做错了什么?任何帮助将不胜感激。

import os
import urllib
import webapp2
from google.appengine.ext import db
import google.appengine.api.images
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers

class MainHandler(webapp2.RequestHandler):
  def get(self):

    upload_url = blobstore.create_upload_url('/upload')
    self.response.out.write('<html><body>')
    self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
    self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit"
        name="submit" value="Submit"> </form>""")
    #self.response.headers['Content-Type'] = 'image/png'

    images = db.GqlQuery("select * from Images")
    serving_url = ""
    if images:
        for x in images:
            serving_url = google.appengine.api.images.get_serving_url(x.key(), 0, False, False)
            self.response.out.write("""<div>Image:<img src="%s"  </div> """ %serving_url)
    else:
        self.response.out.write("""<div>No Image Found</div>""")
    self.response.out.write("""END</body></html>""")

class Images(db.Model):
    image_db = db.BlobProperty()

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
    blob_info = upload_files[0]
    self.redirect('/serve/%s' % blob_info.key())

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, resource):
    resource = str(urllib.unquote(resource))
    blob_info = blobstore.BlobInfo.get(resource)
    self.send_blob(blob_info)

app = webapp2.WSGIApplication([('/', MainHandler),
                               ('/upload', UploadHandler),
                               ('/serve/([^/]+)?', ServeHandler)],
                              debug=True)

1 个答案:

答案 0 :(得分:1)

你在这里犯了一些错误。

首先,您正确使用blobstore存储图像。要在模型中存储blobstore图像的引用,您应该使用db.BlobReferenceProperty

其次,您实际上并未在UploadHandler中存储该引用:

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
    blob_info = upload_files[0]
    instance = Images(image_db=blob_info)
    instance.put()
    self.redirect('/')

最后,您的GQL返回Images实例,而不是blob。因此,您对get_serving_url的致电应该是:

serving_url = images.get_serving_url(x.image_db)