Guest User

Base64 Field for django-rest-framework

a guest
Dec 3rd, 2013
499
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. import base64, imghdr, uuid
  2.  
  3. from django.core.files.base import ContentFile
  4. from django.utils.translation import ugettext_lazy as _
  5. from rest_framework import serializers
  6.  
  7. DEFAULT_CONTENT_TYPE = "application/octet-stream"
  8. ALLOWED_IMAGE_TYPES = (
  9.     "jpeg",
  10.     "jpg",
  11.     "png"
  12.     )
  13.  
  14. class Base64ImageField(serializers.ImageField):
  15.     """
  16.    A django-rest-framework field for handling image-uploads through raw post data.
  17.    It uses base64 for en-/decoding the contents of the file.
  18.    """
  19.  
  20.     def from_native(self, base64_data):
  21.         # Check if this is a base64 string
  22.         if isinstance(base64_data, basestring):
  23.             # Try to decode the file. Return validation error if it fails.
  24.             try:
  25.                 decoded_file = base64.b64decode(base64_data)
  26.             except TypeError:
  27.                 raise serializers.ValidationError(_("Please upload a valid image."))
  28.  
  29.             # Generate file name:
  30.             file_name = str(uuid.uuid4())[:12] # 12 character is more than enough.
  31.             # Get the file name extension:
  32.             file_extension = self.get_file_extension(file_name, decoded_file)
  33.             if file_extension not in ALLOWED_IMAGE_TYPES:
  34.                 raise serializers.ValidationError(_("The type of the image couldn't been determined."))
  35.  
  36.             complete_file_name = file_name + "." + file_extension
  37.  
  38.             data = ContentFile(decoded_file, name=complete_file_name)
  39.  
  40.         return super(Base64ImageField, self).from_native(data)
  41.  
  42.     def get_file_extension(self, filename, decoded_file):
  43.         extension = imghdr.what(filename, decoded_file)
  44.         extension = "jpg" if extension == "jpeg" else extension
  45.         return extension
Advertisement
Add Comment
Please, Sign In to add comment