python3使用requests和requests_toolbelt上傳檔案
阿新 • • 發佈:2022-03-30
1、requests-toolbelt官方文件:https://pypi.org/project/requests-toolbelt/
2、環境安裝
pip install requests-toolbelt
3、
multipart/form-data傳檔案
from requests_toolbelt import MultipartEncoder import requests m = MultipartEncoder( fields={'field0': 'value', 'field1': 'value', 'field2': ('檔名稱', open('檔案地址/file.py', 'rb'), 'text/plain')} ) r = requests.post('http://httpbin.org/post', data=m, headers={'Content-Type': m.content_type})
multipart/form-data表單提交(傳非檔案)
from requests_toolbelt import MultipartEncoder import requests m = MultipartEncoder( fields={'field0': 'value', 'field1': 'value'}) r = requests.post('http://httpbin.org/post', data=m, headers={'Content-Type': m.content_type})
multipart/form-data表單提交(傳圖片)
import requests from requests_toolbelt.multipart import MultipartEncoder image = open(r"D:\xxx.jpg", "rb"), # 讀取模式為二進位制讀取方式 m = MultipartEncoder(fields={ # "file":("圖片的名稱.jpg","圖片的二進位制流","image/jpeg") "file": ("xxxx.jpg", image, "image/jpeg") }) r = requests.post('http://httpbin.org/post',data=m,headers={'Content-Type': m.content_type})
引數也可以使用list型別
from requests_toolbelt import MultipartEncoder import requests m = MultipartEncoder( fields = [ ('source', ('f1.ext', f1, 'application/x-example-mimetype'), ('source', ('f2.ext', f2, 'application/x-example-mimetype'), ] ) r = requests.post('http://httpbin.org/post', data=m, headers={'Content-Type': m.content_type})