简体   繁体   English

在 Django 中上传图像返回错误“UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte”

[英]Uploading image in Django returns error "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte"

So I have a nested serializer and I'm trying to upload an image, the image there but when I try to set it to use it on the serializer I'm getting the error.所以我有一个嵌套的序列化程序,我正在尝试上传图像,图像在那里,但是当我尝试将它设置为在序列化程序上使用它时,我收到了错误。 My code:我的代码:

models.py模型.py

class Pet(models.Model):
   pet_id = models.UUIDField('pet uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True)  
   name = models.CharField('Pet name', max_length=255, null=False, blank=False)

class Attachment(models.Model):
    attachment_id = models.UUIDField('attachment uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True)       
    pet_id = models.ForeignKey(Pet, on_delete=models.CASCADE)
    name = models.FileField(upload_to='photos/', null=False, blank=False)
    upload_at = models.DateTimeField('Time it was uploaded', max_length=50, null=False, blank=False )

serializers.py序列化程序.py

class AttachmentSerializer(serializers.ModelSerializer):    
    class Meta:
        model = Attachment
        fields = ('name','upload_at')

class PetSerializer(serializers.ModelSerializer):
    attachments = AttachmentSerializer(many=True)
    class Meta: 
        model = Pet
        fields = ('pet_id','name', 'attachments')
            
    def create(self, validated_data):
        attachments = validated_data.pop('attachments')
        pet = Pet.objects.create(**validated_data)
        for att in attachments:
            Attachment.objects.create(pet_id=pet, **att)
        return pet

views.py视图.py

parser_classes = (MultiPartParser, FormParser)

def create_pet(self, request):   
    img = BytesIO(request.FILES.get('file_1').read())
    img.seek(0)
    data = Image.open(img) 
    new_data = request.data.copy()
    new_data['attachments'] = [{'name':data, 'upload_at':datetime.now()}]
    serializer = self.get_serializer(data=new_data)         
    if not serializer.is_valid():
       return Response({'error':serializer.errors},status=status.HTTP_400_BAD_REQUEST)

    serializer.save()

    return Response({'data':serializer.validated_data}, status=status.HTTP_201_CREATED)

but I'm getting UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte但我收到UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Stacktrace:堆栈跟踪:

Traceback (most recent call last):
  File "/srv/http/petProject/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/srv/http/petProject/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 202, in _get_response
    response = response.render()
  File "/srv/http/petProject/env/lib/python3.8/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/srv/http/petProject/env/lib/python3.8/site-packages/rest_framework/response.py", line 70, in rendered_content
    ret = renderer.render(self.data, accepted_media_type, context)
  File "/srv/http/petProject/env/lib/python3.8/site-packages/rest_framework/renderers.py", line 100, in render
    ret = json.dumps(
  File "/srv/http/petProject/env/lib/python3.8/site-packages/rest_framework/utils/json.py", line 25, in dumps
    return json.dumps(*args, **kwargs)
  File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps
    return cls(
  File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/srv/http/petProject/env/lib/python3.8/site-packages/rest_framework/utils/encoders.py", line 50, in default
    return obj.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

Any thoughts about this?对此有什么想法吗? Thanks in advance.提前致谢。

The problem was in create_pet in this line:问题出在这一行的create_pet中:

return Response({'data':serializer.validated_data}, status=status.HTTP_201_CREATED)

I was returning the image itself, so in order to not get an error, I just replace the images itself for its name in the attachments before the return.我正在返回图像本身,所以为了不出错,我只是在返回之前在attachments中将图像本身替换为它的名称。 like:喜欢:

files = []
for dicts in serializer.validated_data['attachments']:
    for d in dicts:
        d['name'] = d['name'].name
        files.append(d)

serializer.validated_data['attachments'] = files

That solved the problem.那解决了问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 套接字错误:“UnicodeDecodeError:‘utf-8’编解码器无法解码 position 中的字节 0xff 0:起始字节无效” - Socket error: "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte" 错误 UnicodeDecodeError:'utf-8' 编解码器无法解码 position 中的字节 0xff 0:起始字节无效 - error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte UnicodeDecodeError:'utf-8'编解码器无法解码位置38的字节0xff:无效的起始字节 - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 38: invalid start byte UnicodeDecodeError:“utf-8”编解码器无法解码位置 162 中的字节 0xff:无效起始字节 - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 162: invalid start byte UnicodeDecodeError:“ utf-8”编解码器无法解码位置0的字节0xff:无效的起始字节 - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte 如何解决 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte - How to solve UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Django 和 React 返回 obj.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte - Django and React return obj.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte 可能导致此错误的原因:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 568: invalid start byte - What could cause this error : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 568: invalid start byte UnicodeDecodeError:'utf-8'编解码器无法解码 position 0 中的字节 0xff:读取 csv 时 python 中的无效起始字节错误 - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte error in python while reading a csv file UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0xff:尝试编码时无效的起始字节('utf-8') - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte when I tried to encode('utf-8')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM