初始提交: LiteAdmin 社区平台

This commit is contained in:
张志挺
2026-08-07 14:18:18 +08:00
commit f39008193f
37 changed files with 5447 additions and 0 deletions
+161
View File
@@ -0,0 +1,161 @@
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: (not os.path.isdir(os.path.join(target, x)), x.lower()))
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,
})
return items, subpath
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:
return HTTPResponse.redirect('/admin/login/')
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', '')
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,
})
return HTTPResponse(body=html)
@app.route('/admin/files/download/', methods=['GET'])
async def file_download(request):
user = get_current_user(request)
if not user:
return HTTPResponse.redirect('/admin/login/')
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=['GET'])
async def file_delete(request):
user = get_current_user(request)
if not user:
return HTTPResponse.redirect('/admin/login/')
if not user.is_admin():
return HTTPResponse.error(403, '权限不足')
filepath = request.query_params.get('path', '')
subpath = request.query_params.get('dir', '')
fm.delete(filepath)
return HTTPResponse.redirect('/admin/files/?path={}'.format(subpath))