Reputation: 7587
I am using google app engine with python and jinja framework.
I want to let users upload an image to use it on a thumbnail.
Images will be for thumbnails and not more than 10, so I don't have a reason to not use the database.
Here is my html
<form class="reg-page" method="post" enctype="multipart/form-data" />
<label>Name </label>
<input type="text" class="span12" name="name" value={{name}}>
<label>Description </label>
<textarea class="span12" name="description" value={{description}}></textarea>
<label>Photo </label>
<div class="fileupload fileupload-new" data-provides="fileupload">
<div>
<span class="btn btn-file"><span class="fileupload-new">Select image</span>
<span class="fileupload-exists">Change</span><input name="image" type="file" /></span>
<a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
</div>
</div>
<button class="btn-u pull-right" type="submit">Εγγραφή </button>
</form>
{{test}}
The back-end is simple:
class ImgUpload(db.Model):
name = db.StringProperty()
description = db.StringProperty(multiline=True)
img_img = db.BlobProperty()
class testhandler(BaseHandler):
def get(self):
self.render("test.html")
def post(self):
images = ImgUpload()
name = self.request.get('name')
description = self.request.get('description')
img_img = image = self.request.get("image")
images.img_img = db.Blob(img_img)
images.name = name
images.description = description
images.put()
u = ImgUpload.gql("WHERE name = '%s'"%name).get()
self.response.out.write("""<img src="/test?test=%s"></img>""" %u.key())
app = webapp2.WSGIApplication([("/test",testhandler)
],debug=True)
When I run the code, I see a corrupted image.
Upvotes: 1
Views: 307
Reputation: 12986
When you recieve the post you will need to create a model for storing the image
e.g.
class Image(ndb.Model):
file = ndb.BlobProperty()
filename = ndb.StringProperty()
mimetype = ndb.StringProperty()
size = ndb.IntegerProperty()
width = ndb.IntegerProperty()
height = ndb.IntegerProperty()
You then need to create a handler that maps the url of the image to some code that fetches the image from the datastore, and returns the data sets the content type headers correctly. You could also use properties of the entity in your jinja code to set width and height in img tag,
In your code you are rendering an img tag with
"""<img src="/test?test=%s"></img>""" %u.key())
You now need to map /test?test= to a get handler, and then it needs to do a
self.response.write(<the blobproperty>)
and you need to set the content type of the response to a image/jpeg or whatever image type you are storing. In addition if your serving images to old versions of IE you will also need to set the filename with the image extension.
And don't do the GQL query for the image to construct your <img>
tag, you already have the key of the object with images.key() as soon as you do the images.put()
Upvotes: 1