python3使用requests和requests_toolbelt上传文件

2022/3/30 14:19:26

本文主要是介绍python3使用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})

  



这篇关于python3使用requests和requests_toolbelt上传文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程