依赖
安装 requests 库:
pip install requests
import requests
# 目标 URL
url = "http://abcxxx.com/api/v1/upload/"
# 文件路径
file_path = "/data/logs/123xx.log"
# 打开文件并上传
try:
with open(file_path, 'rb') as file:
files = {'file': file}
response = requests.post(url, files=files)
# 检查响应
if response.status_code == 200:
print("文件上传成功:", response.json())
else:
print("文件上传失败:", response.status_code, response.text)
except FileNotFoundError:
print(f"文件 {file_path} 不存在,请检查路径。")
except Exception as e:
print("发生错误:", str(e))
目标 URL: 替换为 API 的上传地址:http://abcxxx.com/api/v1/upload/。
文件上传:
使用 open 打开文件,设置 rb(二进制模式)。
将文件通过 files 参数上传。
异常处理:
捕获文件不存在的错误。
捕获其他可能的网络或编程异常。
响应处理:
如果服务器返回状态码 200,表示成功。
打印详细的失败信息以便调试。