
from microdot import Microdot, Response , redirect
from wifi import connect_wifi
from scard import SDCard
from machine import SPI, Pin
import os
def is_file(path):
try:
return not (os.stat(path)[0] & 0x4000)
except:
return False
def mount_sd():
try:
spi = SPI(2, baudrate=1_000_000,
sck=Pin(5),
mosi=Pin(6),
miso=Pin(7))
cs = Pin(4, Pin.OUT)
sd = SDCard(spi, cs)
os.mount(sd, '/sd')
print("✅ SD 卡挂载成功:", os.listdir('/sd'))
return True
except Exception as e:
print("❌ SD 卡挂载失败:", e)
return False
connect_wifi()
mount_sd()
Response.default_content_type = 'text/html'
app = Microdot()
@app.route('/')
def index(req):
try:
with open('/sd/www/index.html') as f:
return f.read()
except Exception as e:
return f"<h1>无法加载主页</h1><p>{e}</p>", 500
@app.route('/files')
def list_sd_files(req):
msg = req.args.get('msg', '')
try:
files = os.listdir('/sd')
html = """<!DOCTYPE html><html><head><meta charset='utf-8'><title>SD 文件列表</title></head><body>"""
html += "<h1>📁 SD 卡文件列表</h1>"
if msg:
html += f"<p style='color: green;'>{msg}</p>"
html += """
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">上传文件</button>
</form>
<hr>
<ul>
"""
for name in files:
full_path = '/sd/' + name
if is_file(full_path):
html += f"""
<li>
<a href="/download/{name}">{name}</a>
<form style="display:inline" method="POST" action="/delete">
<input type="hidden" name="filename" value="{name}">
<button type="submit" onclick="return confirm('确定删除文件 {name} 吗?');">删除</button>
</form>
</li>"""
html += "</ul></body></html>"
return html
except Exception as e:
return f"<h1>无法读取 SD 卡文件</h1><p>{e}</p>", 500
@app.route('/delete', methods=['POST'])
def delete_file(req):
filename = req.form.get('filename')
if not filename:
return "未指定文件名", 400
filepath = '/sd/' + filename
if not is_file(filepath):
return "文件不存在", 404
try:
os.remove(filepath)
return redirect(f"/files?msg=文件 {filename} 删除成功!")
except Exception as e:
return f"删除文件失败: {e}", 500
@app.route('/upload', methods=['POST'])
def upload_file(req):
try:
content_type = req.headers.get('Content-Type', '')
if 'multipart/form-data' not in content_type:
return "请求类型错误", 400
boundary = content_type.split("boundary=")[-1]
body = req.body
parts = body.split(b'--' + boundary.encode())
for part in parts:
if b'Content-Disposition' in part and b'filename=' in part:
header, file_data = part.split(b'\r\n\r\n', 1)
header_str = header.decode()
filename = header_str.split('filename="')[-1].split('"')[0]
file_data = file_data.rsplit(b'\r\n', 1)[0]
with open('/sd/' + filename, 'wb') as f:
f.write(file_data)
return redirect(f"/files?msg=文件 {filename} 上传成功!")
return "未找到上传文件", 400
except Exception as e:
return f"上传失败: {e}", 500
@app.route('/download/<filename>')
def download_file(req, filename):
filepath = '/sd/' + filename
if not is_file(filepath):
return '文件不存在', 404
try:
f = open(filepath, 'rb')
return Response(
f,
headers={
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename="{}"'.format(filename)
}
)
except Exception as e:
return f"读取文件失败: {e}", 500
@app.route('/<path:path>')
def serve_static(req, path):
full_path_www = '/sd/www/' + path
if is_file(full_path_www):
try:
return open(full_path_www).read()
except:
return '读取失败', 500
return '404 Not Found', 404
app.run(host='0.0.0.0', port=80)