使用requests的post方法传输多个文件

[python] 2024-05-06 圈点873

摘要:使用requests的post方法传输多个文件的示例方法

使用requests的post方法传输多个文件的示例方法:


假设在html中的input元素有:

<input type="file" name="images" multiple="true" required="true"/>


分析:

只要把文件设到一个元组的列表中,其中元组结构为 (form_field_name, file_info)


示例:

url = 'http://a.com/dopost'
multiple_files = [
 ('images', ('foo.png', open('a.png', 'rb'), 'image/png')),
 ('images', ('bar.png', open('b.png', 'rb'), 'image/png'))]
r = requests.post(url, files=multiple_files)
r.text


强烈建议用二进制模式(binary mode)打开文件。如果用文本模式打开文件,就可能碰到错误。


requests  

感谢反馈,已提交成功,审核后即会显示