Python requests module提供了关于如何在单个请求中上传单个文件的很好的文档:
files = {'file': open('report.xls', 'rb')}我尝试通过使用以下代码扩展该示例,尝试上传多个文件:
files = {'file': [open('report.xls', 'rb'), open('report2.xls, 'rb')]}但它导致了这个错误:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1052, in splittype
match = _typeprog.match(url)
TypeError: expected string or buffer是否可以使用此模块在单个请求中上传文件列表,以及如何上传?
发布于 2013-12-25 14:51:51
要在单个请求中上传具有相同键值的文件列表,您可以创建一个元组列表,每个元组中的第一项作为键值,文件对象作为第二项:
files = [('file', open('report.xls', 'rb')), ('file', open('report2.xls', 'rb'))]发布于 2013-08-12 18:37:35
通过添加多个字典条目,可以上传具有不同密钥值的多个文件:
files = {'file1': open('report.xls', 'rb'), 'file2': open('otherthing.txt', 'rb')}
r = requests.post('http://httpbin.org/post', files=files)发布于 2014-10-30 04:15:18
documentation包含一个明确的答案。
引用:
您可以在一个请求中发送多个文件。例如,假设您要将图像文件上载到具有多个文件字段“images”的HTML表单:
为此,只需将文件设置为(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',
# ...
# }https://stackoverflow.com/questions/18179345
复制相似问题