记录python上传文件的坑

 1 import random
 2 import string
 3 import requests
 4 from requests_toolbelt import MultipartEncoder
 5 
 6 
 7 f = '20191112091254.xlsx' # 文件
 8 # print(f)
 9 
10 url = 'http://xxxx.com'
11 
12 # 随机生成boundary
13 default_boundary = ''.join(random.sample(string.ascii_letters + string.digits, 30))
14 print(default_boundary)
15 
16 # multipartFile为form表单中的key名字
17 # 括号中的第一个值为文件名
18 m = MultipartEncoder(fields={'multipartFile': ('20191112091254.xlsx', open(f, 'rb'), 'text/plain')}, boundary=default_boundary)
19 # print(m)
20 
21 h = {'Authorization': 'Bearer fewi8737912iuiewrg', 'Content-Type': m.content_type}
22 r = requests.post(url , data=m, headers=h)
23 json = r.json()
24 print(json)

 

点赞