- 请求教程
- 请求 - 主页
- 请求 - 概述
- 请求 - 环境设置
- 请求 - Http 请求如何工作?
- 请求 - 处理请求
- 处理 HTTP 请求的响应
- 请求 - HTTP 请求标头
- 请求 - 处理 GET 请求
- 处理 POST、PUT、PATCH 和 DELETE 请求
- 请求 - 文件上传
- 请求 - 使用 Cookie
- 请求 - 处理错误
- 请求 - 处理超时
- 请求 - 处理重定向
- 请求 - 处理历史记录
- 请求 - 处理会话
- 请求 - SSL 认证
- 请求 - 身份验证
- 请求 - 事件挂钩
- 请求 - 代理
- 请求 - 使用请求进行网页抓取
- 请求有用的资源
- 请求 - 快速指南
- 请求 - 有用的资源
- 请求 - 讨论
请求 - 文件上传
在本章中,我们将使用 request 上传文件并读取上传文件的内容。我们可以使用文件参数来完成此操作,如下例所示。
我们将使用http://httpbin.org/帖子上传文件。
例子
import requests myurl = 'https://httpbin.org/post' files = {'file': open('test.txt', 'rb')} getdata = requests.post(myurl, files=files) print(getdata.text)
测试.txt
File upload test using Requests
输出
E:\prequests>python makeRequest.py
{
"args": {},
"data": "",
"files": {
"file": "File upload test using Requests"
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "175",
"Content-Type": "multipart/form-data;
boundary=28aee3a9d15a3571fb80d4d2a94bfd33",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0"
},
"json": null,
"origin": "117.223.63.135, 117.223.63.135",
"url": "https://httpbin.org/post"
}
也可以发送文件的内容,如下所示 -
例子
import requests myurl = 'https://httpbin.org/post' files = {'file': ('test1.txt', 'Welcome to TutorialsPoint')} getdata = requests.post(myurl, files=files) print(getdata.text)
输出
E:\prequests>python makeRequest.py
{
"args": {},
"data": "",
"files": {
"file": "Welcome to TutorialsPoint"
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "170",
"Content-Type": "multipart/form-data;
boundary=f2837238286fe40e32080aa7e172be4f",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0"
},
"json": null,
"origin": "117.223.63.135, 117.223.63.135",
"url": "https://httpbin.org/post"
}