NIKHIL RANE NIKHIL RANE - 1 year ago 290
Python Question

Save base64 image in django file field

I have following input


I want to save this file in file field. What can I do?

class SomeModel(models.Model):
file = models.FileField(upload_to=get_upload_report)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)

I'm trying to do this

def get_file(data):
from django.core.files import File
return File(data)

and save return file to model instance

somemodel.file = get_file(image_base64_data)

but it's gives a following error

AttributeError at /someurl/

'File' object has no attribute 'decode'

Answer Source
import base64

from django.core.files.base import ContentFile
format, imgstr = data.split(';base64,') 
ext = format.split('/')[-1] 

data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) # You can save this as file istance.

Use this code snippet to decode the base64 string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download