Upload photo from Android device to Django backend and save it to database

981 views Asked by At

I have to upload an image from Android device to a web app written in Python and Django. For storing images, I have made use of easy thumbnails.

What I have done so far is convert the image to base64 string to and post it to server. Well this is working perfectly, also if I write the base64 string to png image file it goes smoothly.

Now, I want to save it to the database as far as I know, easy thumbnails save the actual file to some location on server within the app file structure, and saves a link to same in database.

I am not understanding, how do I save the base64 string I receive in POST to my database.

My Model:

class Register(models.Model): 
   image = ThumbnailerImageField(upload_to=filename, blank=True, null=True, max_length=2048)

def filename(inst, fname):
   f = sha256(fname + str(datetime.now())).hexdigest()
   return '/'.join([inst.__class__.__name__, f])
1

There are 1 answers

1
allcaps On BEST ANSWER

The image is not stored in the db. It is stored to disk. Only a reference to the file is stored in the db.

def Article(models.model):
    image = models.ImageField(...)

Somewhere you create a new object:

from django.core.files.base import ContentFile

obj = Article()
data = base64.b64decode(encoded)
# You might want to sanitise `data` here...
# Maybe check if PIL can read the `data`?
obj.image.save('some_file_name.ext', ContentFile(data))
obj.save()