引言
使用http.client
模块进行文件传输
import http.client
import json
# 定义HTTP客户端
conn = http.client.HTTPConnection('www.example.com')
# 准备文件数据
file_path = 'path/to/your/file.txt'
with open(file_path, 'rb') as f:
file_data = f.read()
# 准备POST请求的头部信息
headers = {
'Content-Type': 'multipart/form-data; boundary=boundary'
}
# 准备POST请求的数据
body = [
('file', ('filename.txt', file_data, 'text/plain')),
]
# 发送POST请求
conn.request('POST', '/upload', body=body, headers=headers)
# 获取响应
response = conn.getresponse()
print(response.status, response.reason)
# 读取响应内容
data = response.read()
print(data.decode('utf-8'))
# 关闭连接
conn.close()
使用requests
库进行文件传输
requests
库是一个简单易用的HTTP库,它提供了发送各种HTTP请求的功能。以下是一个使用requests
库进行文件传输的示例:
import requests
# 定义URL和文件路径
url = 'http://www.example.com/upload'
file_path = 'path/to/your/file.txt'
# 发送POST请求,并上传文件
response = requests.post(url, files={'file': open(file_path, 'rb')})
# 获取响应
print(response.status_code, response.reason)
# 读取响应内容
print(response.text)
在这个示例中,我们使用了requests.post
方法,并通过files
参数上传了文件。requests
库会自动处理文件上传的细节,包括设置正确的Content-Type
头部。