Python Requests库 form-data 上传文件操作

请求数据示例:

------WebKitFormBoundaryKLoWgrA4O40MayHM
Content-Disposition: form-data; name="id"

9
------WebKitFormBoundaryKLoWgrA4O40MayHM
Content-Disposition: form-data; name="name"

赵云
------WebKitFormBoundaryKLoWgrA4O40MayHM
Content-Disposition: form-data; name="tel"

13212345678
------WebKitFormBoundaryKLoWgrA4O40MayHM
Content-Disposition: form-data; name="school"

西南科技大学
------WebKitFormBoundaryKLoWgrA4O40MayHM
Content-Disposition: form-data; name="major"

计算机
------WebKitFormBoundaryKLoWgrA4O40MayHM
Content-Disposition: form-data; name="age"

30
------WebKitFormBoundaryKLoWgrA4O40MayHM
Content-Disposition: form-data; name="img"; filename="demo.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryKLoWgrA4O40MayHM--

1.通过data参数和files参数发送请求

import requests

request_url = 'http://www.demo.com/studentInfo/saveNewInfo'
# 构造字典,键值对方式传参
request_data = {
    'id': '9',
    'name': '赵云',
    'tel':'13212345678',
    'school': '西南科技大学',
    'major': '计算机',
    'age': '30'
}
# 上传文件单独构造成以下形式
# 'img' 上传文件的键名
# 'demo' 上传到服务器的文件名,可以和上传的文件名不同
# open('D:/demo.jpg') 打开的文件对象,注意文件路径正确
# 'image/jpeg' Content-Type类型
request_file = {'img':(('demo',open('D:/demo.jpg')),'image/jpeg')}

requests.post(url=request_url, data=request_data, files=request_file)   # url,data,files

2.仅通过files参数模拟文件发送请求

import requests

request_url = 'http://www.demo.com/studentInfo/saveNewInfo'
# 构造字典,键值对方式传参
# 不是文件的构造键值对,键值为一个元组形式,元组第0位为None,第1位为键值.
request_files = {
    'id': (None, '9'),
    'name': (None, '赵云'),
    'tel':(None, '13212345678'),
    'school': (None, '西南科技大学'),
    'major': '计算机',
    'age': '30',
    'img':(('demo',open('D:/demo.jpg')),'image/jpeg')
    # 'img':(None,'','image/jpeg')   不传文件的写法
}

requests.post(url=request_url, files=request_files)     # url,files

猜你喜欢

转载自www.cnblogs.com/milesma/p/12023405.html