将数据存储区中的图像读入<img/>标记

时间:2014-10-14 09:16:29

标签: python google-app-engine google-cloud-datastore image-uploading app-engine-ndb

您好我正在尝试为实体上传图片并将其放入另一个页面进入图片代码,但无法完成。

将整个blob内容写入响应是有效的,但如果我试图将blob内容转换为html页面中的 标记,则不可见。

以下是代码。请帮忙

import webapp2
from google.appengine.ext import ndb
import mimetypes
import logging


HTML_POST_PAGE = \
"""
<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Image Upload</title>
</head>
<body>
<form action="/file_upload" enctype="multipart/form-data" method="post">
    <div><input type="file" name="file"/></div>
    <div><input type="submit" value="Upload"></div>

</form>
</body>
</html>
"""


OUTPUT_HTML_PAGE = """
<!DOCTYPE HTML>
<html lang="en">
<head>
    <title>Image Upload</title>
</head>
<body>
<h1>Serving image dynamically.</h1>
<img src='/dyimg_serve?img_id=%s'></img>
</body>
</html>
"""

#Hardcoded value for Key name
email_id = "ryan@gmail.com"

#Updated Image Upload
class MyUser(ndb.Model):
    file_name = ndb.StringProperty()
    blob = ndb.BlobProperty()


class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.write(HTML_POST_PAGE)

#Handler for image upload
class FileUpload(webapp2.RequestHandler):
    def post(self):
            #Creating entity with fixed id
            my_user = MyUser(id=email_id)

            #Below lines to be added in the main code to put image in datastore
            file_upload = self.request.POST.get("file", None)
            file_name = file_upload.filename
            my_user.file_name = file_name
            my_user.blob = file_upload.file.read()
            userKey = my_user.put()

            #Navigating to other page to read image
            self.response.out.write(OUTPUT_HTML_PAGE)


#Handler to read image into the <img> tag in the OUTPUT_HTML_PAGE 
class DynamicImageServe(webapp2.RequestHandler):
    def get(self):
        oldUser = MyUser.get_by_id(email_id)
        if oldUser != None and oldUser.blob != None:
##            self.response.headers['Content-Type'] = 'image/png'
            self.response.headers[b'Content-Type'] = mimetypes.guess_type(oldUser.file_name)[0]
            self.response.write(oldUser.blob)
        else:
            self.response.write('Error while fetching image data')


application = webapp2.WSGIApplication([('/',MainPage ),('/file_upload',FileUpload),('/dyimg_serve',DynamicImageServe),], debug=True)         

1 个答案:

答案 0 :(得分:1)

您没有在输出页面上设置img标记的src属性。

<img src="/dyimg_serve"></img>