'Incorrect padding when attempting to update profile picture

My project is built on React and Django. I would like to enable users to update profile information. Noticed that I was initially getting a 304 error when it specifically comes to updating the profile picture. and realized that this had something to do with Django requiring multipart form data. I then tried to upload the profile picture using a base64 encoding string, but now getting the error

Incorrect padding

Here is my serializers.py:

#upload profile picture using base64 encoding string instead of raw file (not supported by default)
class Base64ImageField(serializers.ImageField):
    def to_internal_value(self, data):
        from django.core.files.base import ContentFile
        import base64
        import six
        import uuid

        #check if this is base64 string
        if isinstance(data, six.string_types):
            #check if the base64 is in the data format
            if 'data:' in data and ';base64' in data:
                header,data = data.split(';base64,')
            try:
                decoded_file = base64.b64decode(data)
            except TypeError:
                self.fail('invalid_image')

            #Generate file name:
            file_name = str(uuid.uuid4())[:12]
            #Get the file name extension
            file_extension = self.get_file_extension(file_name, decoded_file)
            complete_file_name = "%s.%s" % (file_name, file_extension, )
            data = ContentFile(decoded_file, name=complete_file_name)
        return super(Base64ImageField, self).to_internal_value(data)

    def get_file_extension(self, file_name, decoded_file):
        import imghdr
        extension = imghdr.what(file_name, decoded_file)
        extension = "jpg" if extension == "jpeg" else extension
        return extension

#updating user profile
class UpdateUserSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(required=False)
    city = serializers.CharField(source='profile.city', allow_blank=True, required=False)
    country = serializers.CharField(source='profile.country', allow_blank=True, required=False)
    profile_pic = Base64ImageField(max_length=None, use_url=True, required=False)
        # serializers.ImageField(source='profile.profile_pic', use_url=True, required=False)

    class Meta:
        model = User
        #, 'city', 'country', 'bio'
        fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'profile_pic']
        # fields = UserDetailsSerializer.Meta.fields + ('city', 'country')
        extra_kwargs = {'username': {'required': False},
                        'email': {'required': False},
                        'password': {'required': False},
                        'first_name': {'required': False},
                        'last_name': {'required': False},
                        'city': {'required': False},
                        'country': {'required': False},
                        'profile_pic': {'required': False}
                        }
    def update(self, instance, validated_data):
        profile_data = validated_data.pop('profile', {})
        city = profile_data.get('city')
        country = profile_data.get('country')
        profile_pic = profile_data.get('profile_pic')

        instance = super(UpdateUserSerializer, self).update(instance, validated_data)

        profile = instance.profile
        if profile_data:
            if city:
                profile.city = city
            if country:
                profile.country = country
            if profile_pic:
                profile.profile_pic = profile_pic
            profile.save()
        return instance

I am passing my updated information using this function:

const updateProfile = (userData) => {
        console.log('userData', userData)
        //we pass profile information through token payload, so let's get a new token
        const refreshToken = {
            'refresh': authTokens.refresh
        }
        console.log(refreshToken)
        axios.put(`http://127.0.0.1:8000/update_profile/${userData.user_id}/`, userData)
            .then(res => {
                console.log(res.data)
    ...

Here is a sample of some info I sent



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source