我尝试通过包含
的CURL发布multipart / form-data
- JSON对象
- 流对象pdf和jpeg文件
curl -i -X POST -H
"Authorization":"eyJhbGciOiJIUzI1NiIsImV4cCI6MTQyNjcwNTY4NiwiaWF0IjoxNDI2NzAyMDg2fQ.eyJpZCI6MTc3fQ.yBwLFez2RnxTojLniL8YLItWVvBb90HF_yfhcsyg3lY" -H
"Content-Type:application/multipart/form-data" -d '{"user data": {"preferred_city":"Newyork","within_radious":"5"}}' --data-binary
"uploaded_documents":@mydocument.pdf http://127.0.0.1:5000/api/city
现在,我需要在flask请求对象中读取这个多部分数据。我试过
request.data
它确实打印了数据,但我不确定如何读取流对象并将文件存储到磁盘。
答案 0 :(得分:8)
你的curl命令有一些问题,所有这些都可能导致问题:
application/multipart/form-data
不是有效的MIME类型,所以
Content-Type
无效。对于文件上传,内容类型通常为multipart/form-data
。此外,您不需要指定内容类型,curl将根据参数进行处理。-F
代替-d
会导致curl生成并发布
具有有效边界的multipart/form-data
表格。将它们放在一起会产生这个curl命令:
curl -i -H "Authorization":"eyJhbGciOiJIUzI1NiIsImV4cCI6MTQyNjcwNTY4NiwiaWF0IjoxNDI2NzAyMDg2fQ.eyJpZCI6MTc3fQ.yBwLFez2RnxTojLniL8YLItWVvBb90HF_yfhcsyg3lY" \
-F user_data='{"user data": {"preferred_city":"Newyork","within_radious":"5"}}' \
-F uploaded_documents=@mydocument.pdf \
http://127.0.0.1:5000/api/city
如果您不喜欢curl选择的内容类型(文件将是application / octet-stream),您可以为每个部分指定内容类型:
curl -i -H "Authorization":"eyJhbGciOiJIUzI1NiIsImV4cCI6MTQyNjcwNTY4NiwiaWF0IjoxNDI2NzAyMDg2fQ.eyJpZCI6MTc3fQ.yBwLFez2RnxTojLniL8YLItWVvBb90HF_yfhcsyg3lY" \
-F 'user_data={"user data": {"preferred_city":"Newyork","within_radious":"5"}};type=application/json' \
-F 'uploaded_documents=@mydocument.pdf;type=application/pdf' \
http://127.0.0.1:5000/api/city
最后一个命令将生成如下的HTTP请求:
POST /api/city HTTP/1.1 User-Agent: curl/7.32.0 Host: 127.0.0.1:5000 Accept: */* Authorization:eyJhbGciOiJIUzI1NiIsImV4cCI6MTQyNjcwNTY4NiwiaWF0IjoxNDI2NzAyMDg2fQ.eyJpZCI6MTc3fQ.yBwLFez2RnxTojLniL8YLItWVvBb90HF_yfhcsyg3lY Content-Length: 496 Expect: 100-continue Content-Type: multipart/form-data; boundary=------------------------1ab997efff76fe66 --------------------------1ab997efff76fe66 Content-Disposition: form-data; name="user_data" Content-Type: application/json {"user data": {"preferred_city":"Newyork","within_radious":"5"}} --------------------------1ab997efff76fe66 Content-Disposition: form-data; name="uploaded_documents"; filename="mydocument.pdf" Content-Type: application/pdf this is the mydocument.pdf file. it should be a pdf file, but this is easier to test with. --------------------------1ab997efff76fe66--
然后在Flask中,您可以使用request.form
访问表单数据,例如request.form['user_data']
。由于它是json字符串,您可以使用json.loads(request.form['user_data'])
加载它。