我正在尝试将 base64 编码的图像保存在 django rest 框架中。首先,我们做一个代码,将base64编码后的图片插入到imagefield中进行测试,出现如下错误。
binascii.Error:填充不正确
我不明白的是,我之前使用过相同的代码并没有出现这样的错误。你能帮助我吗?这是我的代码。
serializers.py
from rest_framework import serializers
from .models import post, comment
class Base64ImageField (serializers.ImageField) :
def to_internal_value (self, data) :
from django.core.files.base import ContentFile
import base64
import six
import uuid
if isinstance(data, six.string_types):
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')
file_name = str(uuid.uuid4())[:12]
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
class commentSerializer (serializers.ModelSerializer) :
class Meta :
model = comment
fields = '__all__'
class postSerializer (serializers.ModelSerializer) :
author = serializers.CharField(source='author.username', read_only=True)
image1 = Base64ImageField(use_url=True)
image2 = Base64ImageField(use_url=True)
image3 = Base64ImageField(use_url=True)
image4 = Base64ImageField(use_url=True)
image5 = Base64ImageField(use_url=True)
comment = commentSerializer(many=True, read_only=True)
class Meta:
model = post
fields = ['pk', 'author', 'title', 'text', 'image1', 'image2', 'image3', 'image4', 'image5', 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'comment']
梵蒂冈之花
交互式爱情
慕森卡
MM们
慕桂英546537
相关分类