### Python 3.7 Windows
import requests
from urllib3 import encode_multipart_formdata
#params其它参数 images 图片列表
def uploadFiles(params,images):
url = "接口url"
headers = {}
data = {}
paramsList = []
for key in params:
paramsList.append((key,params[key]))
for image in images:
paramsList.append(("file",(image.get("filename"), open(image.get("filepath"), 'rb').read())))
encode_data = encode_multipart_formdata(paramsList)
data = encode_data[0]
headers['Content-Type'] = encode_data[1]
result = requests.post(url, headers=headers, data=data, proxies={})
return result.text
if __name__ == '__main__':
params = {
"otherParam":"demo"
}
images = [
{
"filepath": r'E:\ITKouSyou\desktop\1.png',
"filename": '1.png'
},
{
"filepath": r'E:\ITKouSyou\desktop\2.png',
"filename": '2.png'
}
]
print("uploadFiles:"+uploadFiles(params,images))
这个方法的关键在encode_multipart_formdata(paramsList)
之前传的参数是字典类似
{"file":[]} 会报以下错误,说明这种方式行不通,而字典不允许多个相同的key,所以这里使用了元组
将其他参数和file文件都添加到元祖里就可以成功了