简体   繁体   中英

How to store base64 image as a file in GAE datastore

I have an image encoded with base 64 that I want to store in my datastore model.

class Surveys(db.Model):
    name = db.StringProperty(required = True)
    text = db.TextProperty(required = True)
    image = db.BlobProperty()
    created = db.DateTimeProperty(auto_now_add = True)

How do I turn the base64 string back into a file that I can put into the database? Below is how I would do it for a normal file.

name = 'test'
text = 'test'
image = self.request.get('img')
s = Surveys(name = name, text = text)
s.image = db.Blob(image)
s.put()

Are you looking for a way to decode base64 data?

You might wish to take a look at the various base64 utilities available with Python. For example, base64.b64decode :

import base64

binary_data = base64.b64decode(base64_encoded_string)

Assuming the JPEG file was properly encoded as base64, this will "reverse" the operation -- returning a string of bytes identical to the content of the original file. All file "meta informations" are lost in the process: you only get back the content of the file. Not its original name, permissions, and so on.

You can either store the base64 string to datastore directly, then decode it during runtime when you need to send the JPEG bytes.

Or do it the other way round... I'd prefer decode the base64 first before storing to datastore as it's more byte efficient and you only need to decode once.

And you don't need the concept of "file" here... you just store the image as bytes, when you need to send it out as JPEG to browser, you just create the proper http headers (eg Content-Type:image/jpeg) and echo/write the bytes in the http body.

To add to everything else (which is all good advice): Consider using ndb (new database) rather than db for the model. If you do a get_by_id() for single image retrieval, ndb will handle the memecache for you. This will really speed up your latency for frequently accessed images. Also if it is a frequently accessed image, add a cache control statement to your response header in addition to the type. HTH. -stevep

self.response.headers['Content-Type'] = 'image/jpeg'
self.response.headers['Cache-Control']  = 'public, max-age=315360000'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM