ESP32 008 MicroPython Web框架库 Microdot 实现的网络文件服务器

发布于:2025-06-28 ⋅ 阅读:(17) ⋅ 点赞:(0)

在这里插入图片描述

#from lib.microdot import Microdot, Response
from microdot import Microdot, Response , redirect
from wifi import connect_wifi
from scard import SDCard
from machine import SPI, Pin
import os


#  替代  if os.path.isfile(full_path_www):
def is_file(path):
    try:
        return not (os.stat(path)[0] & 0x4000)  # 非目录
    except:
        return False
# 挂载 SD 卡
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()

# 根目录 —— 加载 /sd/www/index.html
@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


# 列出 SD 根目录所有文件,可点击下载
# @app.route('/files')
# def list_sd_files(req):
#     try:
#         files = os.listdir('/sd')
#         html = "<!DOCTYPE html><html><head><meta charset='utf-8'><title>SD 文件列表</title></head><body>"
#         html += "<h1>📁 SD 卡文件列表</h1><ul>"
#         for name in files:
#             full_path = '/sd/' + name
#             if is_file(full_path):
#                 html += f'<li><a href="/download/{name}">{name}</a></li>'
#         html += "</ul></body></html>"
#         return html
#     except Exception as e:
#         return f"<h1>无法读取 SD 卡文件</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]  # 去除结束标记

                # 写入到 SD 卡
                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



# 下载接口 —— 浏览器触发下载行为 —— 保持 SD 卡原文件名
@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)