python-3.x - 上传带有请求的文件
问题描述
我使用 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
代码与 swagger 和 post man 一起工作正常,现在我想用 requests 模块上传文件,我的代码是:
files = {"file": open('/home/user/b839.jpeg', 'rb')}
resp = requests.post('http://localhost:8000/api/upload/', files=files)
我用过这个文件。但响应内容是{"file": ["No file was submitted."]}
. 我使用'multipart/form-data'
Content-Type
了任何一个,但我得到了相同的响应。这里有什么问题?
- 编辑 -
Postman 生成代码片段:
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/'
解决方案
从标题中删除了“内容类型”