I'm trying to take a base64-encoded PNG, decode it, then upload it to Google Cloud Storage and get its public URL.
I can do it locally by saving the PNG to file and then uploading it with blob.upload_from_file('picture.png')
, but App Engine doesn't allow write access to its file structure.
This code works locally but not in Google App Engine, where it fails at with open(...
import base64
from google.cloud import storage
def handler(request):
pic = request.POST.get('photograph') #Object like 'data:image/png;base64,iVBORw0KGgoAAAAN…'
data = pic[22:]
png = base64.b64decode(data)
filename = "pic.png"
with open(filename, "wb") as f:
f.write(png)
client = storage.Client.from_service_account_json(os.path.abspath('credentials.json'))
bucket = client.get_bucket('mybucket')
blob = bucket.blob(filename) #create destination uri in bucket
blob.upload_from_file(filename)
image_url = "https://storage.googleapis.com/mybucket/" + filename
The GCS docs say to Use the Blob.upload_from_file(), Blob.upload_from_filename(), or Blob.upload_from_string() method to upload an object.
However none of those methods work for this situation because there is no file, just an encoded PNG object. How can I upload it to gcloud storage?
I'm surely missing something obvious. Any ideas would be much appreciated.