0

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

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)
4

1 回答 1

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 返回图像实例,而不是 blob。所以你的电话get_serving_url应该是:

serving_url = images.get_serving_url(x.image_db)
于 2013-11-03T19:20:30.097 回答