Python使用requests和requests_toolbelt上传文件

1、requests-toolbelt官方文档:https://pypi.org/project/requests-toolbelt/

2、环境安装

pip install requests-toolbelt

3、

multipart/form-data传文件

from requests_toolbelt import MultipartEncoder
import requests
 
m = MultipartEncoder(
    fields={'field0': 'value',
           'field1': 'value',
            'field2': ('文件名称', open('文件地址/file.py', 'rb'), 'text/plain')}
    )
 
r = requests.post('http://httpbin.org/post',
                  data=m,
                  headers={'Content-Type': m.content_type})

multipart/form-data表单提交(传非文件) 

from requests_toolbelt import MultipartEncoder
import requests
 
m = MultipartEncoder(
       fields={'field0': 'value',
               'field1': 'value'})
 
r = requests.post('http://httpbin.org/post',
                  data=m,
                  headers={'Content-Type': m.content_type}) 

multipart/form-data表单提交(传图片)

import requests
from requests_toolbelt.multipart import MultipartEncoder

image = open(r"D:\xxx.jpg", "rb"),  # 读取模式为二进制读取方式

m = MultipartEncoder(fields={
    # "file":("图片的名称.jpg","图片的二进制流","image/jpeg")
    "file": ("xxxx.jpg", image, "image/jpeg")
})

r = requests.post('http://httpbin.org/post',data=m,headers={'Content-Type': m.content_type})

  

参数也可以使用list类型

from requests_toolbelt import MultipartEncoder
import requests
 
m = MultipartEncoder(
    fields = [
    ('source', ('f1.ext', f1, 'application/x-example-mimetype'),
    ('source', ('f2.ext', f2, 'application/x-example-mimetype'),
]
    )
 
r = requests.post('http://httpbin.org/post',
                  data=m,
                  headers={'Content-Type': m.content_type})

  

posted @ 2022-03-30 13:17  北京测试菜鸟  阅读(1556)  评论(0编辑  收藏  举报