Skip to content

Instantly share code, notes, and snippets.

@Keda87
Last active July 25, 2017 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Keda87/0565c97f1b882b4364844fb9b3005404 to your computer and use it in GitHub Desktop.
Save Keda87/0565c97f1b882b4364844fb9b3005404 to your computer and use it in GitHub Desktop.
DRF field to handle base64 encoded string as attachment. Automatically transform it to binary file.
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()
image_output.write(decodestring(b64encoded_file))
image_output.seek(0)
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment