需要用到一个requests的一个辅助工具库requests_toolbelt,代码如下

import os,random,sys
import requests
from requests_toolbelt.multipart import encoder
from math import round
def upload_monitor(monitor):
    print(round(monitor.bytes_read/monitor.len*100,2))

url = 'http://127.0.0.1:18019/upload-file'

headers={}

path=r'C:\file.txt'
filename=path.split('\\')[-1]
multipart_encoder = encoder.MultipartEncoder(
    fields={
        filename: (filename, open(path, 'rb'), 'text/plain')#根据上传文件类型的不同而不同
    },
)
monitor = encoder.MultipartEncoderMonitor(multipart_encoder, upload_monitor)


boundary=multipart_encoder.content_type.split('=')[-1]
headers['Content-Type']=multipart_encoder.content_type
r = requests.post(url, data=monitor, headers=headers)
print(r.text)

参考:

1.https://toolbelt.readthedocs.io/en/latest/uploading-data.html#monitoring-your-streaming-multipart-upload