Document(here):
POST Multiple Multipart-Encoded Files
You can send multiple files in one request. For example, suppose you want to upload image files to an HTML form with a multiple file field ‘images’:
<input type="file" name="images" multiple="true" required="true"/>
To do that, just set files to a list of tuples of
(form_field_name, file_info)
:
>>> url = 'http://httpbin.org/post' >>> multiple_files = [ ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')), ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))] >>> r = requests.post(url, files=multiple_files) >>> r.text { ... 'files': {'images': 'data:image/png;base64,iVBORw ....'} 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a', ... }
Warning
It is strongly recommended that you open files in binary mode. This is because Requests may attempt to provide the
Content-Length
header for you, and if it does this value will be set to the number of bytes in the file. Errors may occur if you open the file in text mode.
TEST:
#!/usr/bin/python3 #-*- coding:utf-8 -*- import requests import json import os import sys def getfile(ppath): pfile = os.listdir(ppath) return pfile def uptest(par=''): url = "" # Request URL post = {"json_msg": json.dumps( \ {"function_name":"upload_proprietor_msg", "params":{"yz_tel" : "", "qy_num" : "19000", "zx_address" : "分享", "qy_firm" : "10000", "yz_is_tg" : 0, "qy_time" : "2017-04-07", "yz_name" : "测试 1", "token" : "30bb34e0-7058-7d7e-28e1-14d63187b44c", "designer_id" : "4"}} )} # pic test ppath = '/home/fhy/' files = [ ('file[]', ('fluidicon.png', open(ppath+'fluidicon.png', 'rb'), 'image/png')), ('file[]', ('qq.jpg', open(ppath+'qq.jpg', 'rb'), 'image/jpg'))] rs = requests.post(url, files=files, data=post) # formatting if par == 'f': print('formatting') jsonen = rs.content.decode('utf-8-sig') strj = json.loads(jsonen) # print (strj) print( json.dumps(strj, ensure_ascii=False, indent=4, sort_keys=True) ) sys.exit() print(rs.text) # print('fhy'*3) uptest()
注意
当时测试遇到只能上传一张的问题,琢磨了好久,仔细一想 html 的 file 标签上传时加”[]”才能实现多图。故将 file 改为 file[]