post多个分块编码的文件(requests高级用法):
你可以在一个请求中发送多个文件。例如,假设你要上传多个图像文件到一个 HTML 表单,使用一个多文件 field 叫做 “images”:
<input type="file" name="images" multiple="true" required="true"/>
要实现,只要把文件设到一个元组的列表中,其中元组结构为 (form_field_name, file_info):
>>> url = 'http://httpbin.org/post'
>>> multiple_files = [
('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]
>>> r = requests.post(url, files=multiple_files)
>>> r.text
{
...
'files': {'images': 'data:image/png;base64,iVBORw ....'}
'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',
...
}
警告
我们强烈建议你用二进制模式(binary mode)打开文件。这是因为 requests 可能会为你提供 header 中的 Content-Length,在这种情况下该值会被设为文件的字节数。如果你用文本模式打开文件,就可能碰到错误。
#元组列表
[
("field1" , ("filename1", open("filePath1", "rb"))),
("field1" , ("filename2", open("filePath2", "rb"), "image/png")),
("field1" , open("filePath3", "rb")),
("field1" , open("filePath4", "rb").read())
]
#字典
{
"field1" : [
("filename1", open("filePath1", "rb")),
("filename2", open("filePath2", "rb"), "image/png"),
open("filePath3", "rb"),
open("filePath4", "rb").read()
]
}
参考:
摘抄自python-requests官方文档高级用法:
http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced
python的requests发送/上传多个文件
https://blog.csdn.net/five3/article/details/74913742/