Last active
February 19, 2023 12:08
-
-
Save yprez/7704036 to your computer and use it in GitHub Desktop.
Django rest framework - Base64 image field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
And when I want to fetch that file? I get "http://some-ip/api/users/17/Raw%20content"
Wuau this method is to convert base64 to image, thank you again, you save my day and my life :D
@s2krish Thanks man! Your comment was useful for me!
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”
I have made this field optional. I want to pass null value to the field but its showing error
@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
Hi please explain where do i use this code?
This is my serializers.py
class Image64Serializer(serializers.ModelSerializer):
class Meta:
model = SampleImage64
fields = ('id', 'image64')
This is models.py
class SampleImage64(models.Model):
image64 = models.ImageField(upload_to('images'))