我使用django rest上传文件
序列化器
class FileSerializer(serializers.Serializer):
file = serializers.FileField()
查看
class FileCreateView(generics.CreateAPIView):
parser_classes = (MultiPartParser,)
serializer_class = api_serializers.FileSerializer
def post(self, request, *args, **kwargs):
serialize_data = self.get_serializer(data=request.data)
if serialize_data.is_valid():
# save file
return response
代码可以用招摇和投递员很好地工作,现在我想使用请求模块上传文件,我的代码是:
files = {"file": open('/home/user/b839.jpeg', 'rb')}
resp = requests.post('http://localhost:8000/api/upload/', files=files)
我使用了这个document。但是响应内容为{"file": ["No file was submitted."]}
。
我也使用过'multipart/form-data'
Content-Type
,但是得到的响应是相同的。怎么了?
-编辑-
邮递员生成代码段:
import requests
url = "http://localhost:8000/api/upload/"
payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"123.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
'Content-Type': "application/x-www-form-urlencoded",
'Cache-Control': "no-cache",
'Postman-Token': "94d50d44-3f06-4e0a-b056"
}
response = requests.request("POST", url, data=payload, headers=headers)
昂首阔步:
curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' -F file=@"123.jpg" 'http://localhost:8000/api/upload/'
答案 0 :(得分:1)
我解决了这个问题。问题出在文件字典上。文件字典的值必须为models.py
的元组,这是起作用的代码:
class SomeModel(models.Model):
field_1 = models.CharField(max_length=100, primary_key=True)
field_2 = models.CharField(max_length=100)
field_3 = models.CharField(max_length=100)
答案 1 :(得分:1)
从标题中删除了“内容类型”