Google App Engine (Python) - upload file (image)

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

class ImageData(ndb.Model): name = ndb.StringProperty(indexed=False) image = ndb.BlobProperty() 

Information is provided by the user using the form (HTML):

 <form name = "input" action = "/register" method = "post"> name: <input type = "text" name = "name"> image: <input type = "file" name = "image"> </form> 

which is then processed:

 class AddProduct(webapp2.RequestHandler): def post(self): imagedata = ImageData(parent=image_key(image_name)) imagedata.name = self.request.get('name') imagedata.image = self.request.get('image') imagedata.put() 

However, when I try to load an image, say, "Book.png", I get an error message: BadValueError: Expected str, got u'Book.png'

Any idea what is going on? I have been working with GAE for some time, but this is the first time I had to use blobs.

I used this link: https://developers.google.com/appengine/docs/python/images/usingimages which uses db, not ndb. I also tried to save the image in a variable first, as in the link: storedInfo = self.request.get('image') and then save it: imagedata.image = ndb.Blob(storedInfo) Which ALSO gives me an error: AttributeError: 'module' object has no attribute 'Blob' Thanks in advance.

+6
source share
3 answers

Had the same problem.

just replace

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

with:

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

also your form should have enctype = "multipart / form-data p>

 <form name = "input" action = "/register" method = "post" enctype="multipart/form-data"> 
+7
source

The documentation that describes how to upload files to Blobstore using an HTML form has a great example: https://developers.google.com/appengine/docs/python/blobstore/#Python_Uploading_a_blob

The form must point to the url generated by blobstore.create_upload_url('/foo') , and must be a subclass of BlobstoreUploadHandler at /foo as follows:

 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 must change your data model so that in ImageData , image ndb.BlobKeyProperty() to ndb.BlobKeyProperty() .

You can submit your image simply from the URL generated by images.get_serving_url(imagedata.image) , optionally images.get_serving_url(imagedata.image) and cropped.

+4
source

You must add enctype="multipart/form-data" in your form 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> 
+2
source

Source: https://habr.com/ru/post/952322/


All Articles