工作中,有一个上传图片的接口。逻辑是这样的,先通过cid获取token,再通过token来上传图片。
获取token这些步骤先忽略,我们来看下上传图片的接口参数格式
POST data: -----------------------------7d159c1302d0y0 Content-Disposition: form-data; name="message" Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit {"delay_time":0,"attachments":[{"area_id":2,"expiretype":1,"form_field":"first_object","metadata":{"alarmtime":"1617068785","alarmtype":3,"cid": 753383264,"devicename":"测试","deviceserial":"68731188250","id":"687311882501519870247"},"url":""}],"body":{},"channel_id":0,"subject":""} -----------------------------7d159c1302d0y0 Content-Disposition: form-data; name="first_object"; filename="pengyuyan.jpg" Content-Type: image/jpeg Content-Transfer-Encoding: binary <actual file content, not shown here> -----------------------------7d159c1302d0y0--
从格式中,可以看到有file文件上传。看具体实现代码
file_path = "C:\Users\admin\Desktop\images\peng1.jpg" data = {'message': '{"delay_time":0,"attachments":[{"area_id":2,"expiretype":1,"form_field":"first_object","metadata":{"alarmtime":"1617088512","alarmtype":3,"cid":753376406,"devicename":"测试","deviceserial":"68731188250","id":"687311882501519870247"},"url":""}],"body":{},"channel_id":0,"subject":"", "topic_id": 2}'} files={ 'first_object':('pengyuyan',open(file_path,'rb'),'image/jpeg')
}
#first_object格式:'first_object':(随意指定文件名,目标文件,文件类型)
res = requests.post(url=url,files=files,data=data)
print(res.text)
参数中,不是文件参数的我们放到data里面,文件格式的,提取请求头name的值作为字典的键,文件键值按照这种格式组织:{'first_object':(随意指定文件名,目标文件,文件类型) }