55 lines
1.6 KiB
Python
55 lines
1.6 KiB
Python
|
|
#!/usr/bin/env python3
|
|||
|
|
"""简易文件上传客户端,用于通过 API 上传文件到临时文件传输服务"""
|
|||
|
|
|
|||
|
|
import requests
|
|||
|
|
import sys
|
|||
|
|
import os
|
|||
|
|
|
|||
|
|
BASE_URL = "http://localhost:5000"
|
|||
|
|
|
|||
|
|
def upload_file(filepath, expiry='24h'):
|
|||
|
|
"""
|
|||
|
|
上传文件到临时文件传输服务
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
filepath: 要上传的文件路径
|
|||
|
|
expiry: 过期时间,可选值: '1h', '24h', '7d'
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
dict: 包含文件信息的字典
|
|||
|
|
"""
|
|||
|
|
if not os.path.exists(filepath):
|
|||
|
|
raise FileNotFoundError(f"文件不存在: {filepath}")
|
|||
|
|
|
|||
|
|
url = f"{BASE_URL}/api/upload"
|
|||
|
|
with open(filepath, 'rb') as f:
|
|||
|
|
files = {'file': (os.path.basename(filepath), f)}
|
|||
|
|
data = {'expiry': expiry}
|
|||
|
|
response = requests.post(url, files=files, data=data)
|
|||
|
|
|
|||
|
|
if response.status_code == 200:
|
|||
|
|
return response.json()
|
|||
|
|
else:
|
|||
|
|
raise Exception(f"上传失败: {response.json().get('error', '未知错误')}")
|
|||
|
|
|
|||
|
|
if __name__ == '__main__':
|
|||
|
|
if len(sys.argv) < 2:
|
|||
|
|
print("用法: python upload_client.py <文件路径> [过期时间]")
|
|||
|
|
print("过期时间可选: 1h, 24h, 7d (默认: 24h)")
|
|||
|
|
sys.exit(1)
|
|||
|
|
|
|||
|
|
filepath = sys.argv[1]
|
|||
|
|
expiry = sys.argv[2] if len(sys.argv) > 2 else '24h'
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
result = upload_file(filepath, expiry)
|
|||
|
|
print(f"上传成功!")
|
|||
|
|
print(f"文件ID: {result['id']}")
|
|||
|
|
print(f"文件名: {result['filename']}")
|
|||
|
|
print(f"分享链接: {result['share_url']}")
|
|||
|
|
if 'filesize' in result:
|
|||
|
|
print(f"文件大小: {result['filesize']} 字节")
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f"错误: {e}")
|
|||
|
|
sys.exit(1)
|