最近嘗試使用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等等,把對應字符替換即可。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
