最近尝试使用request来发送上传文件的post请求,网上找了很多直接post文件的例子,借鉴发现这个方法行不通,于是尝试了另外一种方式:通过第三方包requests_toolbelt讲文件转为数据流来发送请求,尝试成功。
第一类,单个文件,包含在消息体
# -*- coding: utf-8 -*-
import requests
#引入requests_toolbelt包,直接使用数据流来发送上传文件的post请求
from requests_toolbelt.multipart.encoder import MultipartEncoder
url = "http://host/test/bTutorCircle/uploadFile"
m=MultipartEncoder(fields = {
"account":"qatest@chaozhi1v1.com",
"metaTag":"TOPIC_IMAGE",
'file':('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg')
})
headers = {
'Accept-Encoding': "gzip, deflate",
'Content-Type': m.content_type,
}
response = requests.request("POST", url, data=m, headers=headers)
print(response.text)
第二类,多个文件,参数复杂组合情况
# -*- coding: utf-8 -*-
import requests
#引入requests_toolbelt包,直接使用数据流来发送上传文件的post请求
from requests_toolbelt.multipart.encoder import MultipartEncoder
url = "http://host/test/content/inserOrUpdate?token=11E5F02EC251CCBFDBAF0BEE3B23DF35"
m=MultipartEncoder(fields = {
"trainContent":str({"title":"tet","introduction":"
test
","videoLinkType":1,"videoUrl":"","videoDurationM":"2","videoDurationS":0,"videoDuration":120}),"ppt":('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg'),
'cover':('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg'),
'video':('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg')
})
headers = {
'Accept-Encoding': "gzip, deflate",
'Content-Type': m.content_type,
}
response = requests.request("POST", url, data=m, headers=headers)
print(response.text)
附件文件支持多种文件,比如ppt,xls,jmx等等,把对应字符替换即可。