Search code examples
htmlgoogle-app-enginepython-2.7google-cloud-storagewebapp2

How to upload an image from client side form to Google cloud storage bucket?


There is a form that uploads an image. Now I want to store it in Google cloud storage and get back to print on page. The form is : -

<form action="http://master-engine-799.appspot.com/uploadimage" method="POST" enctype="multipart/form-data">
Upload File: <input type="file" name="file"><br>
<input type="submit" name="submit" value="Submit"> 
</form>

and the .py file is

import webapp2
import logging

from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers


class UploadImageHandler(webapp2.RequestHandler):    
  def post(self):        
# code that will upload the image to my bucket on cloud storage    
upload_url = blobstore.create_upload_url('/upload',gs_bucket_name='userimagebucket')

class UploadImageHandler(webapp2.RequestHandler):
    # code to show uploaded image in bucket
app = webapp2.WSGIApplication([('/uploadimage', UploadImageHandler)],
                              debug=True)

Solution

  • from __future__ import with_statement
    
    import cloudstorage as gcs
    
    import webapp2
    import logging
    
    from google.appengine.ext import blobstore
    from google.appengine.ext.webapp import blobstore_handlers
    
    
    
    def CreateFile(filename,imageFile):
      with gcs.open(filename, 'w', content_type = 'image/jpeg') as f:
        f.write(imageFile)
        f.close()
    
    
      blobstore_filename = '/gs' + filename
      return blobstore.create_gs_key(blobstore_filename)
    
    class MyImageHandler(webapp2.RequestHandler):
          def post(self):
            bucket='yourbucketname'
            imageFile = self.request.get('file')
            naemofFile=self.request.get('filename1')
            fileName='/yourbucketname'+'/'+naemofFile
            blob_key = CreateFile(fileName,imageFile)
            logging.info("Blob-Key "+blob_key)
            imageUrl = 'https://%(bucket)s.storage.googleapis.com/%(file)s' % {'bucket':bucket, 'file':naemofFile}
    
        app = webapp2.WSGIApplication([('/myimagehandler', MyImageHandler)],
                                      debug=True)
    

    and the form is like this

    <html>
    <body>
    <form action="http://your-app-id.appspot.com/myimagehandler" method="POST" enctype="multipart/form-data">
       <input type="file" name="file"><br>
    File Name : <input type="text" name="filename1">   <input type="submit" name="submit" value="Submit"> </form>
    </body>
    </html>