最近项目需求需要在同一个请求中上传多个文件,原以为MultipartEncoder不支持,最后肝了4天终于摸索出来了。记录一下,方便后续参考。
上传多个文件
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
file_name_ary= [r'D:\Users\Documents\个人其他工作\资源管理\云下 vm监控数据\zabbix_metrics_vm.memory.util_2021-08-31_11_36.xls',
r'D:\Users\Documents\个人其他工作\资源管理\云下 vm监控数据\zabbix_metrics_system.cpu.util_2021-08-31_13_40.xlsx']
fields = [("mailSendJson", json.dumps(body)),
("files",(os.path.basename(file_name_ary[0]), fo1)),
("files",(os.path.basename(file_name_ary[1]), fo2)),
("boundary","--WebKitFormBoundary9K7xUkVGzyQA6e6h")
]
multipart_encoder = MultipartEncoder(fields)
headers = {"Content-Type": multipart_encoder.content_type}
resp = requests.post(url, headers=headers, data=multipart_encoder)
还可以如下
multipart_encoder = MultipartEncoder(
fields={
"mailSendJson": json.dumps(body),
"files":(os.path.basename(file_name_ary[0]), fo)
# "files": [(os.path.basename(fname), open(fname, "rb") for fname in file_name_ary)]
# "files":self.file_gen(file_name_ary)
},
boundary="--WebKitFormBoundary9K7xUkVGzyQA6e6h"
)
headers = {"Content-Type": multipart_encoder.content_type}
resp = requests.post(url, headers=headers, data=multipart_encoder)
官方github地址:https://github.com/requests/toolbelt/issues/190