UnicodeDecodeError在/api/image/处发生的原因是什么?

huangapple go评论84阅读模式
英文:

Why coming this error: UnicodeDecodeError at /api/image/

问题

我的目标是在响应中显示图像的URL,但它不起作用。我遇到了错误。这里实际上是否可以返回 request.data.get('img')?你能否给我一个解决方案?

serializer.py:

  1. class ImageSerializer(serializers.Serializer):
  2. img = serializers.ImageField(required=False)

views.py:

  1. class ImageView(APIView):
  2. def post(self, request):
  3. serializer = ImageSerializer(data=request.data)
  4. return Response(
  5. {
  6. "processed_image_data": request.data.get('img')
  7. },
  8. status=status.HTTP_200_OK
  9. )

errors:

  1. UnicodeDecodeError at /api/image/
  2. 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
  3. ...
英文:

My goal is to show the image's URL in response but it's not working. I getting errors. Here actually is it possible to return request.data.get('img')? Can you please give me a solution?

serializer.py:

  1. class ImageSerializer(serializers.Serializer):
  2. img = serializers.ImageField(required=False)

views.py:

  1. class ImageView(APIView):
  2. def post(self, request):
  3. serializer = ImageSerializer(data=request.data)
  4. return Response(
  5. {
  6. "processed_image_data": request.data.get('img')
  7. },
  8. status=status.HTTP_200_OK
  9. )

errors:

  1. UnicodeDecodeError at /api/image/
  2. 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
  3. Request Method: POST
  4. Request URL: http://127.0.0.1:8000/api/image/
  5. Django Version: 4.2
  6. Exception Type: UnicodeDecodeError
  7. Exception Value:
  8. 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
  9. Exception Location: D:_Spondon-Bhai_Image-Process\venv\lib\site-packages\rest_framework\utils\encoders.py, line 50, in default
  10. Raised during: app.views.ImageView
  11. Python Executable: D:_Spondon-Bhai_Image-Process\venv\Scripts\python.exe
  12. Python Version: 3.9.5
  13. Python Path:
  14. ['D:\_Spondon-Bhai\_Image-Process',
  15. 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip',
  16. 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs',
  17. 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib',
  18. 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39',
  19. 'D:\_Spondon-Bhai\_Image-Process\\venv',
  20. 'D:\_Spondon-Bhai\_Image-Process\\venv\\lib\\site-packages']
  21. Server time: Wed, 19 Apr 2023 17:23:42 +0000
  22. Unicode error hint
  23. The string that could not be encoded/decoded was: ����
  24. Traceback Switch to copy-and-paste view
  25. D:_Spondon-Bhai_Image-Process\venv\lib\site-packages\django\core\handlers\exception.py, line 55, in inner
  26. return inner
  27. else:
  28. @wraps(get_response)
  29. def inner(request):
  30. try:
  31. response = get_response(request)
  32. except Exception as exc:
  33. response = response_for_exception(request, exc)
  34. return response
  35. return inner
  36. Local vars
  37. D:_Spondon-Bhai_Image-Process\venv\lib\site-packages\django\core\handlers\base.py, line 220, in _get_response
  38. self.check_response(
  39. response,
  40. middleware_method,
  41. name="%s.process_template_response"
  42. % (middleware_method.__self__.__class__.__name__,),
  43. )
  44. try:
  45. response = response.render()
  46. except Exception as e:
  47. response = self.process_exception_by_middleware(e, request)
  48. if response is None:
  49. raise
  50. return response
  51. Local vars

答案1

得分: 1

你遇到的问题是因为响应数据包含二进制图像数据,无法直接包含在JSON响应中。相反,你应该将图像数据转换为可包含在JSON响应中的格式,如base64。你可以尝试以下方式:

  1. import base64
  2. from rest_framework.parsers import MultiPartParser
  3. class ImageView(APIView):
  4. parser_classes = (MultiPartParser,)
  5. def post(self, request):
  6. serializer = ImageSerializer(data=request.data)
  7. if serializer.is_valid():
  8. img = serializer.validated_data.get('img')
  9. img_format = img.image.format.lower()
  10. img_data = img.read()
  11. base64_img_data = base64.b64encode(img_data).decode('utf-8')
  12. return Response(
  13. {
  14. "processed_image_data": f"data:image/{img_format};base64,{base64_img_data}"
  15. },
  16. status=status.HTTP_200_OK
  17. )
  18. else:
  19. return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
英文:

The issue you're encountering is because the response data contains binary image data, which cannot be directly included in a JSON response. Instead, you should convert the image data to a format that can be included in a JSON response, such as base64. You can try something as follows

  1. import base64
  2. from rest_framework.parsers import MultiPartParser
  3. class ImageView(APIView):
  4. parser_classes = (MultiPartParser,)
  5. def post(self, request):
  6. serializer = ImageSerializer(data=request.data)
  7. if serializer.is_valid():
  8. img = serializer.validated_data.get('img')
  9. img_format = img.image.format.lower()
  10. img_data = img.read()
  11. base64_img_data = base64.b64encode(img_data).decode('utf-8')
  12. return Response(
  13. {
  14. "processed_image_data": f"data:image/{img_format};base64,{base64_img_data}"
  15. },
  16. status=status.HTTP_200_OK
  17. )
  18. else:
  19. return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

huangapple
  • 本文由 发表于 2023年4月20日 01:00:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定