要求:依据上图API接口文件说明书,用4个步骤实现multipart form格式的压缩文件上传,过程中需用session.post函数。
求python 案例。
使用CSDN的C知道提供:
requests
库,可以使用以下命令安装:pip install requests
import os
import requests
from requests_toolbelt import MultipartEncoder
api_url = "https://example.com/api/upload"
file_path = "path/to/your/compressed/file.zip"
MultipartEncoder
构建multipart form格式的数据,并将文件添加到数据中。例如:multipart_data = MultipartEncoder(
fields={
"file": (os.path.basename(file_path), open(file_path, "rb"), "application/zip")
}
)
session.post
函数发送请求,并处理响应。例如:response = requests.post(api_url, data=multipart_data, headers={"Content-Type": multipart_data.content_type})
if response.status_code == 200:
print("文件上传成功")
else:
print("文件上传失败,错误代码:", response.status_code)
将以上代码整合到一个完整的Python脚本中:
import os
import requests
from requests_toolbelt import MultipartEncoder
api_url = "https://example.com/api/upload"
file_path = "path/to/your/compressed/file.zip"
multipart_data = MultipartEncoder(
fields={
"file": (os.path.basename(file_path), open(file_path, "rb"), "application/zip")
}
)
response = requests.post(api_url, data=multipart_data, headers={"Content-Type": multipart_data.content_type})
if response.status_code == 200:
print("文件上传成功")
else:
print("文件上传失败,错误代码:", response.status_code)