Skip to content

Instantly share code, notes, and snippets.

Last active February 19, 2023 12:08
Show Gist options
  • Save yprez/7704036 to your computer and use it in GitHub Desktop.
Save yprez/7704036 to your computer and use it in GitHub Desktop.
Django rest framework - Base64 image field
import base64
from django.core.files.base import ContentFile
from rest_framework import serializers
class Base64ImageField(serializers.ImageField):
def from_native(self, data):
if isinstance(data, basestring) and data.startswith('data:image'):
# base64 encoded image - decode
format, imgstr = data.split(';base64,') # format ~= data:image/X,
ext = format.split('/')[-1] # guess file extension
data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext)
return super(Base64ImageField, self).from_native(data)
Copy link

Thanks man!! You save my day!

Copy link

Thanks man! Exactly what I needed

Copy link

Copy link

s2krish commented Jul 29, 2015

from DRF 3.0, from_native is changed to to_internal_value

Copy link

What if i want to make the image optional?, if i don't provide the image it gives error "no file is attached"

Copy link

jyotman commented Aug 28, 2015

Hi please explain where do i use this code?

This is my
class Image64Serializer(serializers.ModelSerializer):
class Meta:
model = SampleImage64
fields = ('id', 'image64')

This is
class SampleImage64(models.Model):
image64 = models.ImageField(upload_to('images'))

Copy link

xtrinch commented Mar 4, 2016

And when I want to fetch that file? I get "http://some-ip/api/users/17/Raw%20content"

Copy link

Wuau this method is to convert base64 to image, thank you again, you save my day and my life :D

Copy link

@s2krish Thanks man! Your comment was useful for me!

Copy link

You can find a more up-to-date (compatible with 3.x) base64 image field in the following Stack Overflow answer.

Django REST Framework upload image: “The submitted data was not a file”

Copy link

I have made this field optional. I want to pass null value to the field but its showing error

Copy link

@kevin-brown thanks, man! You save my day!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment