Django REST Framework文件上传导致“不支持的媒体类型'multipart / form-data'”;错误 [英] Django REST Framework file upload causing an "Unsupported media type 'multipart/form-data'" error

查看:106
本文介绍了Django REST Framework文件上传导致“不支持的媒体类型'multipart / form-data'”;错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我努力通过谷歌搜索来解决此问题,但无法在解决方案,所以这是我的序列化器和API视图。

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

序列化器:

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)    


推荐答案

您应使用 MultiPartParser 而不是FormParser(如果您要发送multipart / form-data)

You should use the MultiPartParser instead of the FormParser if you're sending multipart/form-data.

这篇关于Django REST Framework文件上传导致“不支持的媒体类型'multipart / form-data'”;错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆