先看效果:
代码如下:
import os
from flask import Flask, send_from_directory, abort, request, render_template_stringapp = Flask(__name__)# 设置允许访问的根目录(根据需求修改)
BASE_DIR = os.path.expanduser('/') # 默认用户主目录
# BASE_DIR = 'C:\\' # 或者指定为C盘根目录(Windows)
# BASE_DIR = '/' # 或者指定为根目录(Linux/Mac)# 简单的HTML模板
HTML_TEMPLATE = '''
<!DOCTYPE html>
<html>
<head><title>文件管理器 - {{ path }}</title><style>body { font-family: Arial, sans-serif; margin: 20px; }h1 { color: #333; }ul { list-style-type: none; padding: 0; }li { padding: 5px 0; }a { text-decoration: none; color: #0066cc; }a:hover { text-decoration: underline; }.file { color: #666; }.dir { color: #009933; font-weight: bold; }.breadcrumb { margin-bottom: 20px; }</style>
</head>
<body><h1>文件管理器</h1><div class="breadcrumb"><a href="/?path=">根目录</a>{% if path %}{% for part in path.split('/') %}{% if part %}/ <a href="/?path={{ path.split(part)[0] }}{{ part }}">{{ part }}</a>{% endif %}{% endfor %}{% endif %}</div>{% if parent_dir is not none %}<div><a href="/?path={{ parent_dir }}" class="dir">.. (上级目录)</a></div>{% endif %}<ul>{% for dir_name, dir_path in directories %}<li><a href="/?path={{ dir_path }}" class="dir"> {{ dir_name }}</a></li>{% endfor %}{% for file_name, file_path in files %}<li><a href="/?path={{ file_path }}" class="file">{{ file_name }}</a></li>{% endfor %}</ul>
</body>
</html>
'''@app.route('/')
def index():# 获取路径参数,默认为BASE_DIRpath = request.args.get('path', '')full_path = os.path.join(BASE_DIR, path)# 安全检查:确保路径在BASE_DIR下if not os.path.abspath(full_path).startswith(os.path.abspath(BASE_DIR)):abort(403) # 禁止访问if not os.path.exists(full_path):abort(404) # 路径不存在if os.path.isfile(full_path):# 如果是文件,直接提供下载return send_from_directory(os.path.dirname(full_path), os.path.basename(full_path), as_attachment=True)else:# 如果是目录,列出文件files = []dirs = []try:for item in os.listdir(full_path):item_path = os.path.join(full_path, item)if os.path.isdir(item_path):dirs.append((item, os.path.join(path, item)))else:files.append((item, os.path.join(path, item)))except PermissionError:abort(403) # 无权限访问# 计算上级目录parent_dir = os.path.dirname(path.rstrip('/'))if parent_dir == path.rstrip('/'):parent_dir = None # 已经在根目录return render_template_string(HTML_TEMPLATE,path=path,parent_dir=parent_dir,directories=dirs,files=files,base_dir=BASE_DIR)if __name__ == '__main__':# 启动服务器print(f"文件管理服务器已启动,访问 http://localhost:8000/")print(f"根目录: {BASE_DIR}")print("按 Ctrl+C 停止服务器")app.run(host='0.0.0.0', port=8000)