Handle Base64 Encoded Binary File in DRF

I’m writing a simple class for DRF field for handling base64 string for attachment both image and file. I’m using DRF 3 at this case.

import cStringIO
import six
import uuid
from base64 import decodestring
from mimetypes import guess_type, guess_extension
from django.core.files.uploadedfile import SimpleUploadedFile
class Base64CharField(serializers.CharField):
This field will accept image/file attachment as base64 image
encoded and transform it to binary file.
def _base64_to_binary(self, data):
Convert given base64 encoded file.
# Remove noise: data:image/jpeg;base64, from base64 encoded file.
b64encoded_file = raw.split(',')[1] if len(raw.split(',')) > 1 else ''
file_type, _ = guess_type(raw)
extension = guess_extension(file_type)
image_output = cStringIO.StringIO()
filename = '{name}{ext}'.format(name=uuid.uuid4().hex, ext=extension)
return SimpleUploadedFile(filename, image_output.read(), content_type=file_type)
def to_representation(self, value):
return value.url
def to_internal_value(self, data):
if not isinstance(data, six.string_types):
msg = 'Incorrect type. Expected a string, but got %s'
raise serializers.ValidationError(msg % type(data).__name__)
if not ('data:' in data and ';base64,' in data):
msg = 'Invalid base64 format'
raise serializers.ValidationError(msg)
return self._base64_to_binary(data)
view raw fields.py hosted with ❤ by GitHub

And here is how to use it following below.

class MyModelSerializer(serializers.ModelSerializer):
    company_logo = Base64CharField(required=False)

    class Meta:
        model = MyModel
        fields = '__all__'

Feel free to use and improve my code. 😀

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.