A basic example of uploading an image, saving it in the datastore and serving the image.
fileupload.py:
import webapp2
from google.appengine.ext import ndb
import mimetypes
class Images(ndb.Model):
file_name = ndb.StringProperty()
blob = ndb.BlobProperty()
class FileUpload(webapp2.RequestHandler):
def post(self):
file_upload = self.request.POST.get("file", None)
file_name = file_upload.filename
image = Images(id=file_name, file_name=file_name, blob=file_upload.file.read())
image.put()
self.response.headers[b'Content-Type'] = mimetypes.guess_type(image.file_name)[0]
self.response.write(image.blob)
class ImgServe(webapp2.Requesthandler):
def get(self, resource):
image = ndb.Key('Images', resource).get()
self.response.headers[b'Content-Type'] = mimetypes.guess_type(image.file_name)[0]
self.response.write(image.blob)
Here is the static form to post the image:
<!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>
Routing the form post:
webapp2.Route(r'/file_upload', handler='fileupload.FileUpload')
Routing for the image server: <img alt="test" src="/img_serve/test.png" />
webapp2.Route(r'/img_serve/<resource:(.*)>', handler='fileupload.ImgServe'))