接口测试如何实现文件上传
- python+requests对正常文件上传是很简单的,但是对于Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryJ7KNDCQwPqBqWy1c 这样Content-Type带有boundary的就要做MultipartEncoder处理了。
- 如上传头像这个接口。
#encoding=utf-8
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
session = requests.session()
#首先需要登录提取token或者seesion信息,才能更换头像。这个省略了。
#这是接口上传图片的代码
url = "http://xxxxxxx.html"
#上传图片所用到的字段都放在fields中
multipart_encoder = MultipartEncoder(
fields={
"id": "WU_FILE_0",
"name": "qiqiu.PNG",
"type": "image/png",
"Content-Type": "application/octet-stream",
"file": (
"qiqiu.png", open('E:\images\qq.PNG', 'rb'), 'image/png')
},
#这个boundary对应的内容可以按如下直接写或者用random函数生成对应的格式。
boundary='-----------------------------2385610611750'
)
#这个headers中的content-type要用multipart_encoder去获取。
session.headers['Content-Type'] = multipart_encoder.content_type
result = session.post(url,data=multipart_encoder)
print(result.json())
后记:content-type用multipart/form-data; boundary=----WebKitFormBoundaryJ7KNDCQwPqBqWy1c这样拼接会出错,至于为什么还有待进去学习。