Search code examples
pythongoogle-app-enginegoogle-cloud-storagewebapp2

how to upload image using google cloud client library on cloud storage in python?


i want to upload image on cloud storage. I wrote following code to upload on GCS.

class FormHandler(webapp2.RequestHandler):    # form to upload image
   def get(self):
      upload_url = blobstore.create_upload_url('/upload',gs_bucket_name='mybucketname')
      logging.info("Upload URL: "+upload_url)
      self.response.out.write('<html><body>')
      self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' %          upload_url)      # ImageUploadHandler
     self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit"
    name="submit" value="Submit"> </form></body></html>""")

class ImageUploadHandler(blobstore_handlers.BlobstoreDownloadHandler):
   def get(self, resource):
    self.response.out.write('Uploaded')  

app = webapp2.WSGIApplication([('/image/formHandler',FormHandler),('/image/upload/([^/]+)?',ImageUploadHandler)],debug=True)

above code is running and image got uploaded on my bucket with weired name. I want to upload it with a specific name. And how can i access particular image from bucket.


Solution

  • 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='youbucketname'
        imageFile = self.request.get('file')
        nameOfFile = self.request.get('filename1')
        fileName = '/youbucketname' + '/' + nameOfFile
        blob_key = CreateFile(fileName, imageFile)
        imageUrl = 'https://%(bucket)s.storage.googleapis.com/%(file)s' % {'bucket':bucket, 'file':naemofFile}
        logging.info("Image-URL " + imageUrl)
    
    app = webapp2.WSGIApplication([('/myimagehandler', MyImageHandler)],
                                  debug=True)