use*_*455 21 python-requests multiple-file-upload
Python 请求模块提供了有关如何在单个请求中上传单个文件的良好文档:
files = {'file': open('report.xls', 'rb')}
Run Code Online (Sandbox Code Playgroud)
我试图通过使用此代码来尝试上传多个文件来扩展该示例:
files = {'file': [open('report.xls', 'rb'), open('report2.xls, 'rb')]}
Run Code Online (Sandbox Code Playgroud)
但它导致了这个错误:
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
Run Code Online (Sandbox Code Playgroud)
是否可以使用此模块在单个请求中上载文件列表,以及如何?
Rya*_*Fau 28
要在单个请求中上载具有相同键值的文件列表,可以创建元组列表,其中每个元组中的第一项作为键值,文件对象作为第二项:
files = [('file', open('report.xls', 'rb')), ('file', open('report2.xls', 'rb'))]
Run Code Online (Sandbox Code Playgroud)
Luk*_*asa 16
通过添加多个字典条目,可以上载具有不同键值的多个文件:
files = {'file1': open('report.xls', 'rb'), 'file2': open('otherthing.txt', 'rb')}
r = requests.post('http://httpbin.org/post', files=files)
Run Code Online (Sandbox Code Playgroud)
Wad*_*son 11
该文档包含一个明确的答案.
引:
您可以在一个请求中发送多个文件.例如,假设您要将图像文件上载到具有多个文件字段"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',
# ...
# }
Run Code Online (Sandbox Code Playgroud)
如果您有表单中的文件并希望将其转发到其他 URL 或 API。下面是一个示例,其中包含多个文件和其他表单数据以转发到其他 URL。
images = request.files.getlist('images')
files = []
for image in images:
files.append(("images", (image.filename, image.read(), image.content_type)))
r = requests.post(url="http://example.com/post", data={"formdata1": "strvalue", "formdata2": "strvalue2"}, files=files)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22203 次 |
| 最近记录: |