Saturday, January 4, 2014

GAE: The Amazingly Easy Way of Uploading and Serving Images Using Blobstore

One recommended way of uploading images to GAE is by using blobstoreHere is a quick breakdown of the doc to help you achieve this fast:


imports:
import os
import urllib
import webapp2

from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
serve the form HTML. this form performs the POST to GAE with the selected files data:
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></body></html>""")
add a handler for receiving the POST data (binary content of the file). the last line in this function is to redirect the response to the location from where the file could be downloaded:
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())
add handler to serve the image that you uploaded using the UploadHandler described above:
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)
and finally, define the routes for the app:
app = webapp2.WSGIApplication([('/', MainHandler),
                           ('/upload', UploadHandler),
                           ('/serve/([^/]+)?', ServeHandler)],
                            debug=True)

No comments:

Post a Comment