Multipart Parser In Django rest framework

2019-07-29 00:25发布

I'm trying to upload image using django rest framework. But I had a problem with that , when I'm using postman form it upload image successfully, but when I'm trying to type json as row in postman it returns to me this error.

"The submitted data was not a file. Check the encoding type on the form."

here my code:

serializer.py

class UserImageCreateSerializer(serializers.HyperlinkedModelSerializer):
    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())

    class Meta:
        model = UserImages
        fields = ('user', 'image',)

view.py

class UserImageAPICreateView(ListCreateAPIView):
    queryset = UserImage.objects.all()
    serializer_class = UserImageCreateSerializer
    permission_classes = [AllowAny, AllowAnonymous]

my request:

{
"User": 79,
"image": "/path/to/image.jpg" }

note: when I use postman form it uploaded successfully and when use django rest framework HTML form it works too

I dont know what mistake I did.

so, any one has the solution please help me.

1条回答
欢心
2楼-- · 2019-07-29 01:09

you can not upload a image file by just giving a file path in your json upload data like this:

{
"image": "/path/to/image.jpg"
}

If you send like this django will treat image data as normal string not a file

This is why you keep getting this error

"The submitted data was not a file. Check the encoding type on the form."

you need to send image data, not a image path.

here is python request example of upload image https://stackoverflow.com/a/45611449/2679465

查看更多
登录 后发表回答