Django rest框架中的Multipart Parser [英] Multipart Parser In Django rest framework
问题描述
我正在尝试使用django rest框架上传图片。但是我有一个问题,当我使用邮递员表单时,它可以成功上传图像,但是当我尝试在邮递员中将json作为行键入时,它会向我返回此错误。
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."
这里是我的代码:
serializer.py
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]
我的请求:
{
用户:79,
图像: /path/to/image.jpg
}
{
"User": 79,
"image": "/path/to/image.jpg" }
注意:当我使用邮递员形式成功上传时,以及使用django rest框架HTML形式时也可行
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.
推荐答案
您不能通过仅在json上传数据
中提供文件路径来上传图像,
{
"image": "/path/to/image.jpg"
}
如果这样发送,django会将图像数据视为普通字符串而不是文件
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.
这是上传图像
https:/的python请求示例/stackoverflow.com/a/45611449/2679465
这篇关于Django rest框架中的Multipart Parser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!