Google App Engine (Python) - Uploading a file (image)

前端 未结 3 1510
难免孤独
难免孤独 2020-12-28 10:48

I want the user to be able to upload images to Google App Engine. I have the following (Python):

class ImageData(ndb.Model):
     name = ndb.StringProperty(i         


        
相关标签:
3条回答
  • 2020-12-28 11:15

    Had the same prob.

    just replace

    imagedata.image = self.request.get('image')
    

    with:

    imagedata.image = str(self.request.get('image'))
    

    also your form needs to have enctype="multipart/form-data

    <form name = "input" action = "/register" method = "post" enctype="multipart/form-data">
    
    0 讨论(0)
  • 2020-12-28 11:25

    There is a great example in the documentation that describes how to upload files to the Blobstore using a HTML form: https://developers.google.com/appengine/docs/python/blobstore/#Python_Uploading_a_blob

    The form should point to a url generated by blobstore.create_upload_url('/foo') and there should be a subclass of the BlobstoreUploadHandler at /foo like this:

    class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
      def post(self):
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        imagedata = ImageData(parent=image_key(image_name))
        imagedata.name = self.request.get('name')
        imagedata.image = blob_info.key()
        imagedata.put()
    

    For this to work, you should change your data model such that in ImageData, image referes to a ndb.BlobKeyProperty().

    You can serve your image simply from a url generated by images.get_serving_url(imagedata.image), optionally resized and cropped.

    0 讨论(0)
  • 2020-12-28 11:29

    You must add enctype="multipart/form-data" to your form in order for this to work

    <form name = "input" action = "/register" method = "post" enctype="multipart/form-data">
        name: <input type = "text" name = "name">
        image: <input type = "file" name = "image">
    </form>
    
    0 讨论(0)
提交回复
热议问题