一尘不染

Django REST Framework文件上传导致“不支持的媒体类型'multipart / form-data'”错误

python

我是Django和Django REST
Framework的新手。我有以下序列化程序类,用于与其他信息一起上传文件。但是,当我使用上传的文件运行API端点时,结果是这样的:

HTTP 415 Unsupported Media Type
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "detail": "Unsupported media type \"multipart/form-data; boundary=----WebKitFormBoundaryybZ07gjZAqvcsZw3\" in request."
}

我通过谷歌搜索努力解决了这个问题,但无法解决,因此这里是我的序列化程序和API视图。

序列化器:

class ExampleSerializer(serializers.Serializer):

    example_id = serializers.IntegerField()
    description = serializers.CharField(allow_blank=True)
    example_file = serializers.FileField(allow_empty_file=True)

    def create_requirement_line(self):
        request = self.context['request']

        requirement_line = ExampleService().example_method(
            example_id=self.validated_data['example_id'],
            description=self.validated_data['description'],
            example_file=self.validated_data['example_file']
    )
    return requirement_line

视图:

 class RequirementLineAPIView(BaseCreateAPIView):

    serializer_class = ExampleSerializer
    parser_classes = (FormParser,)

    def post(self, request, format=None,*args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            try:
                example_variable = serializer.example_method()
                return Response(example_variable, status=status.HTTP_200_OK)

            except ValidationError as e:
                return Response(e.message, status=status.HTTP_400_BAD_REQUEST)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

阅读 1022

收藏
2021-01-20

共1个答案

一尘不染

如果要发送multipart / form-data,则应使用MultiPartParser而不是FormParser。

2021-01-20