python-上传文件的几种方式
生活随笔
收集整理的這篇文章主要介紹了
python-上传文件的几种方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一種:
from requests_toolbelt import MultipartEncoder import requests# from_data上傳文件,注意參數名propertyMessageXml data = MultipartEncoder(fields={'propertyMessageXml': ('filename', open('D:/123.xml', 'rb'), 'text/xml')}) requests.post(url=url,data=data,headers={ 'Content-Type': data.content_type})#raw上傳文件 file = open('D:/123.xml','rb') requests.post(url=url,data=file.read(),headers={'Content-Type':'text/xml'})#binary上傳文件 files={'file':open('D:/123.xml','rb')} requests.post(url=url,files=files,headers={'Content-Type':'binary'})第二種:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import requests,glob from urllib3 import encode_multipart_formdatadef upload_file(url=None,path=None,file_path=None):if path:for file_path in glob.glob(path + '\*'): #批量文件data={}data['file'] = (file_path.split("/")[-1], open(file_path, 'rb').read()) # 名稱,讀文件encode_data = encode_multipart_formdata(data)res = requests.post(url, headers={'Content-Type':encode_data[1]},data=encode_data[0])return res.textif file_path:data = {}data['file'] = (file_path.split("/")[-1], open(file_path, 'rb').read()) # 名稱,讀文件encode_data = encode_multipart_formdata(data)res = requests.post(url, headers={'Content-Type': encode_data[1]}, data=encode_data[0])return res.text總結
以上是生活随笔為你收集整理的python-上传文件的几种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python衍生特征
- 下一篇: python-自定义@修饰符