基本方式一:
r = requests.post(‘http://httpbin.org/post‘, files={‘file‘: open(‘report.xls‘, ‘rb‘)})
方式二(带其他参数):
import requests import json session = requests.session() url = "http://cdht-sentinel.testing.bbdops.com/api/v1.0/auth/sso/login?t=669259" data = { "ip": "--", "location": "--", "password": "71b44033d3814ca82c7d079e046d6765", "systemState": 2, "username": "adminc" } headers = { "Connection": "keep-alive", "Content-Encoding": "gzip", "Content-Type": "application/json;charset=UTF-8" } # 登录,获取cookie response = session.post(url=url, data=json.dumps(data), headers=headers) ret = json.loads(response.text) print("登录成功?:", ret.get(‘success‘)) # 上传文件 url_upload = "http://cdht-sentinel.testing.bbdops.com/api/v1.0/building/company/employees/import?t=640796" files = {‘file‘: open(‘0‘, ‘rb‘)} ret_upload = session.post(url_upload, data={‘buildingId‘: 23}, files=files) print(ret_upload) print(ret_upload.text) print(ret_upload.content)
方式三(不使用requests.session(),而采用原生方式):
import requests # 原生方式登录,得到cookie response = requests.post(url="http://cdht-sentinel.testing.bbdops.com/api/v1.0/auth/sso/login?t=862637", json={"ip": "182.150.28.190", "location": "四川省成都市", "password": "71b44033d3814ca82c7d079e046d6765", "systemState": 2, "username": "adminc"}) cookies = response.cookies # 上传图片时带上cookie response = requests.post(url="http://cdht-sentinel.testing.bbdops.com/api/v1.0/building/file/upload?t=670869", files={"file": open("1920_1080.jpg", "rb")}, cookies=cookies) print(response.text) # 上传图片成功