Upload image to Appengine Datastore using BlobStore and Endpoints

804 views Asked by At

How can I upload a file/image to the Appengine Datastore using blobStore? I'm using Google Cloud Endpoints.

This is my model:

class ProductImage(EndpointsModel):
    _message_fields_schema = ('product', 'enable', 'image')
    product = ndb.KeyProperty(Product)
    image = ndb.BlobKeyProperty(required=True)
    enable = ndb.BooleanProperty(default=True)

How can I test it from API Explorer? At the frontend I'm using AngularJS.

1

There are 1 answers

0
Ben Margolin On

I couldn't figure out a way to do this with just Endpoints; I had to have a hybrid server with part-endpoints application, part-webapp2 blobstore_handlers application. If you use the webapp2 stuff as per the Blobstore upload examples for those parts, it works. For example, the flow should be:

  1. Client requests an upload URL (use Endpoints for this call, and have it basically do blobstore.create_upload_url(PATH)
  2. Client uploads image to the given URL, which is handled by your blobstore_handlers.BlobstoreUploadHandler method, which pulls out the upload and dumps the blob_info.key() (in JSON, for example)
  3. Client calls createProduct or whatever, an Endpoint, and passes back the blobkey it just received, along with the rest of your ProductImage model. You may want to call get_serving_url in that method and stash it in your model, it shouldn't change later.
  4. Clients can then use that stashed serving url to view image.

Also I had a lot of "fun" with the BlobKeyProperty. In dev deployments, everything worked fine, but in 'production', I'd get invalid image errors while calling get_serving_url() on the stored blobkey. I think this might be due to the blobs actually not being bitmaps, though, and dev not caring.