import random
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
file_key = "xxx"
file_crt = "xxx"
url = "http://xxx"
# 方法一, 使用MultipartEncoder方法
def test_upload():
multipart_encoder = MultipartEncoder(
fields={
'name': "aaa", # 请求参数
'private_key_file': ('local.ifeilian.cn.key', open(file_key, 'rb'), 'application/x-x509-ca-cert'), # 文件数据
'cert_file': ('local.ifeilian.cn.crt', open(file_crt, 'rb'), 'application/x-iwork-keynote-sffkey') # 文件数据
},
boundary='-----------------------------' + str(random.randint(1e28, 1e29 - 1)) # 分隔表单
)
headers["Content-Type"] = multipart_encoder.content_type # 设置 boundary
res = requests.post(url=url, data=multipart_encoder, headers=headers)
print(res.json())
# 方法二 表单数据和文件数据分别发送
def test_upload():
data = { # 表单数据
'key1': 'testcert',
'key2': 'testcert',
}
files = { # 文件数据
'cert_file': ("filename_xxx1", "file_binary_data1", "application/x-x509-ca-cert"),
'private_key_file': ("filename_xxx2", "file_binary_data2", "application/x-iwork-keynote-sffkey"),
}
res = requests.post(url=url, files=files, data=data, headers=headers)
print(res.json())
python使用requests上传多文件
于 2023-10-10 17:48:24 首次发布