Reputation: 5543
Hi I am trying to upload an image for an entity and get it into another page into an image tag but cannot get it done.
Writing in whole blob content into response is working but it is not visible if am trying to get the blob content into an tag in a html page.
Following is the code. Please help
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 = "[email protected]"
#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)
Upvotes: 0
Views: 249
Reputation: 3859
You are not setting the src attribute of your img tag on your output page.
<img src="/dyimg_serve"></img>
Upvotes: 1