import os import shutil import datetime import mimetypes from server import HTTPResponse from auth import get_current_user class FileManager: def __init__(self, upload_dir='uploads'): self.upload_dir = os.path.abspath(upload_dir) os.makedirs(self.upload_dir, exist_ok=True) def _safe_path(self, path): full = os.path.normpath(os.path.join(self.upload_dir, path)) if not full.startswith(self.upload_dir): return None return full def list_files(self, subpath=''): target = self._safe_path(subpath) if not target or not os.path.isdir(target): return [], '' items = [] try: entries = os.listdir(target) # 按修改时间倒序排列(最新的在前) entries.sort(key=lambda x: os.path.getmtime(os.path.join(target, x)), reverse=True) except PermissionError: return [], subpath for name in entries: full = os.path.join(target, name) rel = os.path.join(subpath, name) if subpath else name is_dir = os.path.isdir(full) stat = os.stat(full) modified = datetime.datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M') size = '' if not is_dir: s = stat.st_size if s < 1024: size = '{}B'.format(s) elif s < 1024 * 1024: size = '{:.1f}KB'.format(s / 1024) else: size = '{:.1f}MB'.format(s / (1024 * 1024)) items.append({ 'name': name, 'path': rel, 'is_dir': is_dir, 'size': size, 'modified': modified, 'ext': name.split('.')[-1].lower() if not is_dir and '.' in name else '', }) return items, subpath def search_files(self, keyword): """搜索文件名包含关键词的文件""" if not keyword: return [] keyword = keyword.lower() results = [] for root, dirs, files in os.walk(self.upload_dir): for name in files: if keyword in name.lower(): full = os.path.join(root, name) rel = os.path.relpath(full, self.upload_dir) stat = os.stat(full) modified = datetime.datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M') s = stat.st_size if s < 1024: size = '{}B'.format(s) elif s < 1024 * 1024: size = '{:.1f}KB'.format(s / 1024) else: size = '{:.1f}MB'.format(s / (1024 * 1024)) results.append({ 'name': name, 'path': rel, 'is_dir': False, 'size': size, 'modified': modified, 'ext': name.split('.')[-1].lower() if '.' in name else '', }) # 按修改时间倒序 results.sort(key=lambda x: x['modified'], reverse=True) return results def parent_path(self, subpath): if not subpath: return '' parts = subpath.replace('\\', '/').split('/') if len(parts) <= 1: return '' return '/'.join(parts[:-1]) def upload(self, subpath, filename, content): target = self._safe_path(subpath) if not target: return False, '路径无效' filepath = os.path.join(target, filename) try: with open(filepath, 'wb') as f: f.write(content) return True, '上传成功' except Exception as e: return False, str(e) def delete(self, filepath): target = self._safe_path(filepath) if not target: return False, '路径无效' if not os.path.exists(target): return False, '文件不存在' try: if os.path.isdir(target): shutil.rmtree(target) else: os.remove(target) return True, '删除成功' except Exception as e: return False, str(e) def download(self, filepath): target = self._safe_path(filepath) if not target or not os.path.isfile(target): return None mime_type, _ = mimetypes.guess_type(target) if mime_type is None: mime_type = 'application/octet-stream' with open(target, 'rb') as f: content = f.read() filename = os.path.basename(target) return HTTPResponse(status=200, body=content, content_type=mime_type, headers={'Content-Disposition': 'attachment; filename="{}"'.format(filename)}) def setup_file_routes(app, template_engine, upload_dir='uploads', get_admin_models_func=None): fm = FileManager(upload_dir) @app.route('/admin/files/', methods=['GET', 'POST']) async def file_browser(request): user = get_current_user(request) if not user or not user.is_admin(): return HTTPResponse.error(403, '权限不足') request.current_user = user if request.method == 'POST': if 'file' in request.files: file_data = request.files['file'] subpath = request.form.get('path', '') success, msg = fm.upload(subpath, file_data['filename'], file_data['content']) return HTTPResponse.redirect('/admin/files/?path={}'.format(subpath)) subpath = request.query_params.get('path', '') search_q = request.query_params.get('q', '').strip() if search_q: files = fm.search_files(search_q) current_path = '搜索: {}'.format(search_q) parent = '' else: files, current_path = fm.list_files(subpath) parent = fm.parent_path(subpath) admin_models = {} if get_admin_models_func: admin_models = get_admin_models_func(request) html = template_engine.render('admin/files.html', { 'request': request, 'current_user': user, 'admin_models': admin_models, 'files': files, 'current_path': current_path, 'parent_path': parent, 'search_q': search_q, }) return HTTPResponse(body=html) @app.route('/admin/files/download/', methods=['GET']) async def file_download(request): user = get_current_user(request) if not user or not user.is_admin(): return HTTPResponse.error(403, '权限不足') filepath = request.query_params.get('path', '') resp = fm.download(filepath) if resp is None: return HTTPResponse.error(404, '文件未找到') return resp @app.route('/admin/files/delete/', methods=['POST']) async def file_delete(request): user = get_current_user(request) if not user or not user.is_admin(): return HTTPResponse.error(403, '权限不足') filepath = request.form.get('path', '') subpath = request.form.get('dir', '') fm.delete(filepath) return HTTPResponse.redirect('/admin/files/?path={}'.format(subpath))