一键扫码上传文件
import os, socket, qrcode, cgi, urllib.parse, shutil, datetime
from http.server import HTTPServer, BaseHTTPRequestHandler
from pathlib import Path
UPLOAD_DIR = "uploads"
DOWNLOAD_DIR = "to_phone"
os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args): pass
def send_html(self, html, status=200):
self.send_response(status)
self.send_header("Content-type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(html.encode('utf-8'))
def do_GET(self):
if self.path == '/':
self.send_html('''
<meta name="viewport" content="width=device-width">
<h2>🚀 扫码助手</h2>
<a href="/upload" style="display:block;margin:15px;padding:12px;background:#007AFF;color:white;text-decoration:none;border-radius:8px;">📤 上传文件</a>
<a href="/download" style="display:block;margin:15px;padding:12px;background:#34C759;color:white;text-decoration:none;border-radius:8px;">📥 下载PC文件</a>
<button onclick="let m=prompt('输入文字消息');m&&fetch('/text',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'c='+encodeURIComponent(m)}).then(()=>alert('✅ 已发送'))" style="margin:15px;padding:12px;background:#FF9500;color:white;border:none;border-radius:8px;">💬 发文字</button>
''')
elif self.path == '/upload':
self.send_html(f'''
<meta name="viewport" content="width=device-width">
<h2>📤 上传文件</h2>
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="files" multiple required><br><br>
<button type="submit" style="padding:10px 20px;background:#007AFF;color:white;border:none;border-radius:6px;">上传</button>
</form>
<a href="/">← 返回</a>
''')
elif self.path == '/download':
files = [f.name for f in Path(DOWNLOAD_DIR).iterdir() if f.is_file()]
links = ''.join(f'<li><a href="/f/{urllib.parse.quote(f)}">{f}</a></li>' for f in sorted(files))
self.send_html(f'''
<meta name="viewport" content="width=device-width">
<h2>📥 下载文件</h2>
<p>把文件放进电脑的 <code>{DOWNLOAD_DIR}</code> 文件夹即可下载。</p>
<ul>{links or "<li>暂无文件</li>"}</ul>
<a href="/">← 返回</a>
''')
elif self.path.startswith('/f/'):
fname = urllib.parse.unquote(self.path[3:])
path = os.path.join(DOWNLOAD_DIR, os.path.basename(fname))
if os.path.exists(path):
self.send_response(200)
self.send_header("Content-Disposition", f'attachment; filename="{os.path.basename(path)}"')
self.end_headers()
with open(path, 'rb') as f: shutil.copyfileobj(f, self.wfile)
else:
self.send_error(404)
else:
self.send_error(404)
def do_POST(self):
if self.path == '/upload':
form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD': 'POST'})
files = form['files']
if not isinstance(files, list): files = [files]
for f in files:
if f.filename:
name = os.path.basename(f.filename)
base, ext = os.path.splitext(name)
counter = 1
save_path = os.path.join(UPLOAD_DIR, name)
while os.path.exists(save_path):
save_path = os.path.join(UPLOAD_DIR, f"{base}_{counter}{ext}")
counter += 1
with open(save_path, 'wb') as out: out.write(f.file.read())
print(f"📥 已保存: {save_path}")
self.send_html('<h3 style="color:green">✅ 上传成功!</h3><script>setTimeout(()=>location="/",2000)</script>')
elif self.path == '/text':
length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(length).decode()
msg = urllib.parse.parse_qs(body).get('c', [''])[0]
if msg.strip():
with open(os.path.join(UPLOAD_DIR, "messages.txt"), "a", encoding="utf-8") as log:
log.write(f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}\n")
print(f"💬 收到文字: {msg}")
self.send_html('<h3>✅ 文字已接收!</h3>')
else:
self.send_error(400)
def get_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
except: return "127.0.0.1"
if __name__ == "__main__":
import sys
port = 8081
ip = get_ip()
url = f"http://{ip}:{port}"
print("🚀 扫码上传助手已启动!")
print(f"📁 文件保存在当前目录的 'uploads' 文件夹")
print(f"📤 想让手机下载PC文件?把文件放进 'to_phone' 文件夹\n")
qr = qrcode.QRCode(); qr.add_data(url); qr.print_ascii(invert=True)
print(f"\n🌐 手机扫码地址: {url}\n")
print("⏳ 等待上传...(按 Ctrl+C 停止)\n")
HTTPServer(('', port), Handler).serve_forever()