简体   繁体   中英

Django REST Framework file upload causing an “Unsupported media type 'multipart/form-data'” error

I am newbie in Django and Django REST Framework. I have the following serializer class which I am using to upload a file along other information. But, while I run the API endpoint with uploaded file, the result is something like this:

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."
}

I tried hard by googling to solve this issue, but cannot come out in a solution, so here is my serializer and API views.

Serializer:

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

View:

 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)    

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

Raised if there are no parsers that can handle the content type of the request data when accessing request.DATA or request.FILES.

check Django REST Framework2 documentation

import suitable parser

from rest_framework.parsers import MultiPartParser, FormParser, JSONParser

class SampleView(APIView):
    parser_classes = (MultiPartParser,FormParser,JSONParser)

尝试使用 FileField 解析器在 django rest 中使用解析器

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM