python requests files参数,单字段发送多个文件

post多个分块编码的文件(requests高级用法):
你可以在一个请求中发送多个文件。例如,假设你要上传多个图像文件到一个 HTML 表单,使用一个多文件 field 叫做 “images”:

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

要实现,只要把文件设到一个元组的列表中,其中元组结构为 (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',
  ...
}

警告
我们强烈建议你用二进制模式(binary mode)打开文件。这是因为 requests 可能会为你提供 header 中的 Content-Length,在这种情况下该值会被设为文件的字节数。如果你用文本模式打开文件,就可能碰到错误。

#元组列表
[
  ("field1" , ("filename1", open("filePath1", "rb"))),
  ("field1" , ("filename2", open("filePath2", "rb"), "image/png")), 
  ("field1" , open("filePath3", "rb")),
  ("field1" , open("filePath4", "rb").read())
]
#字典
{
  "field1" : [
                 ("filename1", open("filePath1", "rb")), 
                 ("filename2", open("filePath2", "rb"), "image/png"), 
                 open("filePath3", "rb"),
                 open("filePath4", "rb").read()
               ]
}

参考:
摘抄自python-requests官方文档高级用法:
http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced
python的requests发送/上传多个文件
https://blog.csdn.net/five3/article/details/74913742/

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值