python通過介面上傳文字或圖片等檔案
阿新 • • 發佈:2021-01-20
介面說明
- Conteny-Type 需要設定multipart/form-data
- 檔案型別:text/txt,圖片如 images/png等
- 準備好後臺介面
程式碼
import logging
import os
import requests
logging.basicConfig(level=logging.INFO)
class BatchUpload:
def __init__(self, path):
self.path = path
self.url = 'http://localhost:9090/system/dict/uploadDictBatch'
def upload_api(self):
"""
上傳檔案到介面
:return:
"""
for root, dirs, file_names in os.walk(self.path):
for file in file_names:
logging.info('>>> 上傳檔案,name=' + file)
file_data = {
"file": (file, open(os.path.join(self.path, file), 'rb'), 'text/txt')
}
r = requests.post(url=self.url, files=file_data)
logging.info('>>> ' + str(r.status_code))
logging.info('>>> ' + r.text)
# 解析json
if __name__ == '__main__':
BatchUpload(r'C:\Users\fanling\Desktop\test').upload_api()
注意:不要新增content-type引數!
總結
上面程式碼可用。