This commit is contained in:
2026-04-18 15:08:57 +08:00
commit 2a67f56512
13 changed files with 2729 additions and 0 deletions

14
nas-uploader/.env.example Normal file
View File

@@ -0,0 +1,14 @@
# NAS图片存储根目录部署时修改为实际路径
NAS_DATA_PATH=/volume1/nas_data
# 服务端口
PORT=5000
# 允许的图片格式(小写,逗号分隔)
ALLOWED_EXTENSIONS=jpg,jpeg,png,gif,webp
# 单次上传最大文件数量
MAX_FILES_COUNT=100
# 单张图片最大大小MB
MAX_FILE_SIZE_MB=20

31
nas-uploader/.gitignore vendored Normal file
View File

@@ -0,0 +1,31 @@
# Python
__pycache__/
*.py[cod]
*.pyo
*.egg-info/
dist/
build/
*.egg
venv/
.venv/
# 环境配置(包含敏感信息,不上传)
.env
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# 日志
*.log
nohup.out
# 测试数据
test_*/

287
nas-uploader/app.py Normal file
View File

@@ -0,0 +1,287 @@
import os
import re
import uuid
import shutil
from datetime import datetime
from flask import Flask, request, jsonify, render_template
from config import (
NAS_DATA_PATH, PORT, ALLOWED_EXTENSIONS,
MAX_FILES_COUNT, MAX_FILE_SIZE_MB, ALLOWED_MIME_TYPES
)
app = Flask(__name__)
# ========== 工具函数 ==========
def get_camp_folders():
"""获取所有训练营文件夹列表,按期数排序"""
if not os.path.exists(NAS_DATA_PATH):
os.makedirs(NAS_DATA_PATH, exist_ok=True)
return []
folders = []
for name in os.listdir(NAS_DATA_PATH):
full_path = os.path.join(NAS_DATA_PATH, name)
if os.path.isdir(full_path) and re.match(r'^训练营\d+期$', name):
folders.append(name)
# 按期数数字排序
folders.sort(key=lambda x: int(re.search(r'\d+', x).group()) if re.search(r'\d+', x) else 0)
return folders
def get_class_folders(camp_name):
"""获取某个训练营下的所有班级文件夹,按班号排序"""
camp_path = os.path.join(NAS_DATA_PATH, camp_name)
if not os.path.exists(camp_path):
return []
classes = []
for name in os.listdir(camp_path):
full_path = os.path.join(camp_path, name)
if os.path.isdir(full_path) and re.match(r'^\d+班$', name):
classes.append(name)
# 按班号数字排序
classes.sort(key=lambda x: int(re.search(r'\d+', x).group()) if re.search(r'\d+', x) else 0)
return classes
def validate_file(file):
"""验证上传文件是否合法,返回 (是否合法, 错误原因)"""
if not file or not file.filename:
return False, "空文件"
# 检查文件大小
file.seek(0, os.SEEK_END)
size = file.tell()
file.seek(0)
if size > MAX_FILE_SIZE_MB * 1024 * 1024:
return False, f"文件超过 {MAX_FILE_SIZE_MB}MB 限制"
if size == 0:
return False, "空文件"
# 检查扩展名
ext = file.filename.rsplit('.', 1)[-1].lower() if '.' in file.filename else ''
if ext not in ALLOWED_EXTENSIONS:
return False, f"不支持的格式: {ext}"
# 检查MIME类型
mime = file.mimetype
expected_mime = ALLOWED_MIME_TYPES.get(ext)
if expected_mime and mime and not mime.startswith(expected_mime.split('/')[0]):
return False, f"MIME类型不匹配: {mime}"
return True, None
def generate_filename(original_name, camp_name, class_name):
"""生成新文件名:训练营{n}期-{x}班-{时间戳}-{随机数}.{扩展名}"""
camp_match = re.search(r'(\d+)', camp_name)
class_match = re.search(r'(\d+)', class_name)
camp_num = camp_match.group(1) if camp_match else '?'
class_num = class_match.group(1) if class_match else '?'
now = datetime.now()
timestamp = now.strftime('%Y%m%d%H%M%S')
random_str = uuid.uuid4().hex[:6]
ext = original_name.rsplit('.', 1)[-1].lower() if '.' in original_name else 'jpg'
return f"训练营{camp_num}期-{class_num}班-{timestamp}-{random_str}.{ext}"
def get_unique_filepath(dir_path, filename):
"""获取不冲突的文件路径,若存在则追加序号"""
filepath = os.path.join(dir_path, filename)
if not os.path.exists(filepath):
return filepath
# 分离文件名和扩展名
name, ext = os.path.splitext(filename)
counter = 1
while True:
new_name = f"{name}-{counter}{ext}"
new_path = os.path.join(dir_path, new_name)
if not os.path.exists(new_path):
return new_path
counter += 1
def ensure_folders(camp_name, class_name):
"""确保训练营和班级文件夹存在,不存在则创建"""
camp_path = os.path.join(NAS_DATA_PATH, camp_name)
class_path = os.path.join(camp_path, class_name)
stat_file = os.path.join(camp_path, '统计.md')
created_camp = False
if not os.path.exists(camp_path):
os.makedirs(camp_path, exist_ok=True)
created_camp = True
if not os.path.exists(class_path):
os.makedirs(class_path, exist_ok=True)
# 如果训练营是新创建的,初始化统计文件
if created_camp and not os.path.exists(stat_file):
update_statistics(camp_name)
return camp_path, class_path
def update_statistics(camp_name):
"""更新某个训练营的统计.md文件"""
camp_path = os.path.join(NAS_DATA_PATH, camp_name)
stat_file = os.path.join(camp_path, '统计.md')
if not os.path.exists(camp_path):
return
# 扫描所有班级文件夹
class_stats = []
total = 0
for name in os.listdir(camp_path):
full_path = os.path.join(camp_path, name)
if not os.path.isdir(full_path):
continue
if not re.match(r'^\d+班$', name):
continue
# 统计该班级下的图片数量
count = 0
for fname in os.listdir(full_path):
fpath = os.path.join(full_path, fname)
if os.path.isfile(fpath):
ext = fname.rsplit('.', 1)[-1].lower() if '.' in fname else ''
if ext in ALLOWED_EXTENSIONS:
count += 1
class_stats.append((name, count))
total += count
# 按班号排序
class_stats.sort(key=lambda x: int(re.search(r'\d+', x[0]).group()) if re.search(r'\d+', x[0]) else 0)
# 写入统计文件
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
lines = [
f"# {camp_name} 图片统计",
"",
f"更新时间:{now}",
f"图片总数:{total}",
"",
"| 班级 | 图片数量 |",
"|------|----------|",
]
for class_name, count in class_stats:
lines.append(f"| {class_name} | {count} |")
with open(stat_file, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines) + '\n')
# ========== 页面路由 ==========
@app.route('/')
def index():
return render_template('index.html')
# ========== API 路由 ==========
@app.route('/api/folders', methods=['GET'])
def api_folders():
"""获取所有训练营及其下的班级文件夹"""
folders = []
for camp_name in get_camp_folders():
classes = get_class_folders(camp_name)
folders.append({
'name': camp_name,
'classes': classes,
})
return jsonify({'folders': folders})
@app.route('/api/upload', methods=['POST'])
def api_upload():
"""上传图片"""
camp_name = request.form.get('folder', '').strip()
class_name = request.form.get('class', '').strip()
files = request.files.getlist('files')
# 参数校验
if not camp_name or not re.match(r'^训练营\d+期$', camp_name):
return jsonify({'success': False, 'error': '无效的训练营名称'}), 400
if not class_name or not re.match(r'^\d+班$', class_name):
return jsonify({'success': False, 'error': '无效的班级名称'}), 400
if not files:
return jsonify({'success': False, 'error': '未选择文件'}), 400
if len(files) > MAX_FILES_COUNT:
return jsonify({'success': False, 'error': f'单次最多上传 {MAX_FILES_COUNT}'}), 400
# 确保文件夹存在
camp_path, class_path = ensure_folders(camp_name, class_name)
# 逐个处理文件
uploaded = []
failed = []
has_new_upload = False
for file in files:
# 验证文件
valid, reason = validate_file(file)
if not valid:
failed.append({
'filename': file.filename if file.filename else '未知文件',
'status': 'failed',
'reason': reason,
})
continue
# 生成文件名并保存
new_filename = generate_filename(file.filename, camp_name, class_name)
filepath = get_unique_filepath(class_path, new_filename)
try:
file.save(filepath)
uploaded.append({
'filename': os.path.basename(filepath),
'status': 'success',
})
has_new_upload = True
except Exception as e:
failed.append({
'filename': file.filename,
'status': 'failed',
'reason': str(e),
})
# 如果有新文件上传成功,更新统计
if has_new_upload:
try:
update_statistics(camp_name)
except Exception:
pass # 统计更新失败不影响上传结果
return jsonify({
'success': len(uploaded) > 0,
'uploaded': uploaded,
'failed': failed,
})
# ========== 启动 ==========
if __name__ == '__main__':
# 确保存储目录存在
if not os.path.exists(NAS_DATA_PATH):
os.makedirs(NAS_DATA_PATH, exist_ok=True)
print(f"已创建存储目录: {NAS_DATA_PATH}")
print(f"服务启动在 http://0.0.0.0:{PORT}")
app.run(host='0.0.0.0', port=PORT, debug=False)

29
nas-uploader/config.py Normal file
View File

@@ -0,0 +1,29 @@
import os
from dotenv import load_dotenv
# 加载 .env 文件
load_dotenv()
# NAS图片存储根目录
NAS_DATA_PATH = os.getenv('NAS_DATA_PATH', '/volume1/nas_data')
# 服务端口
PORT = int(os.getenv('PORT', '5000'))
# 允许的图片格式
ALLOWED_EXTENSIONS = os.getenv('ALLOWED_EXTENSIONS', 'jpg,jpeg,png,gif,webp').split(',')
# 单次上传最大文件数量
MAX_FILES_COUNT = int(os.getenv('MAX_FILES_COUNT', '100'))
# 单张图片最大大小MB
MAX_FILE_SIZE_MB = int(os.getenv('MAX_FILE_SIZE_MB', '20'))
# 允许的MIME类型映射
ALLOWED_MIME_TYPES = {
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'png': 'image/png',
'gif': 'image/gif',
'webp': 'image/webp',
}

View File

@@ -0,0 +1,2 @@
flask==3.0.0
python-dotenv==1.0.0

32
nas-uploader/start.sh Normal file
View File

@@ -0,0 +1,32 @@
#!/bin/bash
# NAS图片上传系统 - 启动脚本
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"
# 检查 .env 文件是否存在
if [ ! -f .env ]; then
echo "错误:未找到 .env 配置文件"
echo "请复制 .env.example 为 .env 并修改配置:"
echo " cp .env.example .env"
exit 1
fi
# 检查是否在虚拟环境中
if [ -z "$VIRTUAL_ENV" ]; then
# 尝试激活本地虚拟环境
if [ -d "venv" ]; then
source venv/bin/activate
echo "已激活虚拟环境: venv"
fi
fi
# 检查依赖
python3 -c "import flask" 2>/dev/null
if [ $? -ne 0 ]; then
echo "正在安装依赖..."
pip3 install -r requirements.txt --break-system-packages
fi
echo "启动服务..."
python3 app.py

View File

@@ -0,0 +1,537 @@
/* ========== Reset & Base ========== */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "PingFang SC", "Microsoft YaHei", sans-serif;
background: #f0f2f5;
color: #333;
line-height: 1.6;
min-height: 100vh;
}
.container {
max-width: 720px;
margin: 0 auto;
padding: 20px 16px 40px;
}
/* ========== Header ========== */
.header {
text-align: center;
padding: 24px 0 20px;
}
.header h1 {
font-size: 24px;
font-weight: 600;
color: #1a1a2e;
}
.subtitle {
color: #888;
font-size: 14px;
margin-top: 6px;
}
/* ========== Folder Section ========== */
.folder-section {
background: #fff;
border-radius: 12px;
padding: 20px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.form-group {
margin-bottom: 14px;
}
.form-group:last-child {
margin-bottom: 0;
}
.form-group label {
display: block;
font-size: 14px;
font-weight: 500;
color: #555;
margin-bottom: 6px;
}
.form-group select {
width: 100%;
height: 44px;
padding: 0 14px;
border: 1.5px solid #d9d9d9;
border-radius: 8px;
font-size: 15px;
color: #333;
background: #fafafa;
appearance: none;
-webkit-appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23999' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 14px center;
cursor: pointer;
transition: border-color 0.2s, box-shadow 0.2s;
}
.form-group select:focus {
outline: none;
border-color: #4f6ef7;
box-shadow: 0 0 0 3px rgba(79, 110, 247, 0.1);
background-color: #fff;
}
.form-group select:disabled {
background: #f5f5f5;
color: #bbb;
cursor: not-allowed;
}
/* ========== Upload Section ========== */
.upload-section {
background: #fff;
border-radius: 12px;
padding: 20px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
/* Select Area */
.select-area {
text-align: center;
padding: 30px 20px;
border: 2px dashed #d9d9d9;
border-radius: 10px;
transition: border-color 0.2s, background 0.2s;
}
.select-area:hover {
border-color: #4f6ef7;
background: #f8f9ff;
}
.select-icon {
font-size: 40px;
margin-bottom: 10px;
}
.select-area p {
color: #666;
font-size: 14px;
}
.select-area .hint {
color: #aaa;
font-size: 12px;
margin-top: 4px;
}
/* ========== Buttons ========== */
.btn {
display: inline-block;
padding: 10px 24px;
border: none;
border-radius: 8px;
font-size: 15px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
user-select: none;
-webkit-user-select: none;
}
.btn:active {
transform: scale(0.97);
}
.btn-primary {
background: #4f6ef7;
color: #fff;
}
.btn-primary:hover {
background: #3d5ce0;
}
.btn-primary:disabled {
background: #b0bfee;
cursor: not-allowed;
transform: none;
}
.btn-secondary {
background: #f0f2f5;
color: #555;
margin-top: 12px;
}
.btn-secondary:hover {
background: #e4e6eb;
}
.btn-danger {
background: #ff4d4f;
color: #fff;
padding: 4px 12px;
font-size: 12px;
}
.btn-danger:hover {
background: #e63e40;
}
.btn-small {
padding: 4px 12px;
font-size: 12px;
border-radius: 6px;
}
.btn-large {
width: 100%;
padding: 14px;
font-size: 16px;
margin-top: 16px;
}
/* ========== Preview Section ========== */
.preview-section {
margin-top: 20px;
}
.preview-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
font-size: 14px;
color: #555;
}
.preview-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
gap: 10px;
max-height: 300px;
overflow-y: auto;
padding: 4px;
}
.preview-item {
position: relative;
aspect-ratio: 1;
border-radius: 8px;
overflow: hidden;
border: 1px solid #eee;
}
.preview-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.preview-item .remove-btn {
position: absolute;
top: 4px;
right: 4px;
width: 22px;
height: 22px;
background: rgba(0, 0, 0, 0.5);
color: #fff;
border: none;
border-radius: 50%;
font-size: 14px;
line-height: 22px;
text-align: center;
cursor: pointer;
opacity: 0;
transition: opacity 0.2s;
}
.preview-item:hover .remove-btn {
opacity: 1;
}
.preview-item .file-name {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
color: #fff;
font-size: 10px;
padding: 2px 4px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* ========== Progress Section ========== */
.progress-section {
margin-top: 20px;
}
.progress-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
font-size: 14px;
color: #555;
}
.progress-percent {
font-weight: 600;
color: #4f6ef7;
}
.progress-bar {
width: 100%;
height: 8px;
background: #eee;
border-radius: 4px;
overflow: hidden;
margin-bottom: 16px;
}
.progress-fill {
height: 100%;
width: 0%;
background: linear-gradient(90deg, #4f6ef7, #7c8cf8);
border-radius: 4px;
transition: width 0.3s ease;
}
.file-progress-list {
display: flex;
flex-direction: column;
gap: 8px;
max-height: 250px;
overflow-y: auto;
}
.file-progress-item {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 10px;
background: #fafafa;
border-radius: 8px;
font-size: 13px;
}
.file-progress-item .status-icon {
font-size: 16px;
flex-shrink: 0;
width: 20px;
text-align: center;
}
.file-progress-item .file-info {
flex: 1;
min-width: 0;
}
.file-progress-item .file-info .name {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: #333;
}
.file-progress-item .file-info .detail {
font-size: 11px;
color: #999;
}
.file-progress-item .mini-progress {
width: 60px;
height: 4px;
background: #eee;
border-radius: 2px;
overflow: hidden;
flex-shrink: 0;
}
.file-progress-item .mini-progress .mini-fill {
height: 100%;
background: #4f6ef7;
border-radius: 2px;
transition: width 0.2s;
}
.file-progress-item.status-success .status-icon {
color: #52c41a;
}
.file-progress-item.status-failed .status-icon {
color: #ff4d4f;
}
.file-progress-item.status-failed {
background: #fff2f0;
}
/* ========== Result Section ========== */
.result-section {
background: #fff;
border-radius: 12px;
padding: 20px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.result-header {
margin-bottom: 16px;
}
.result-header h2 {
font-size: 18px;
font-weight: 600;
color: #1a1a2e;
margin-bottom: 4px;
}
.result-summary {
font-size: 14px;
color: #888;
}
.result-summary .success-count {
color: #52c41a;
font-weight: 600;
}
.result-summary .fail-count {
color: #ff4d4f;
font-weight: 600;
}
.result-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
gap: 10px;
max-height: 400px;
overflow-y: auto;
}
.result-item {
position: relative;
aspect-ratio: 1;
border-radius: 8px;
overflow: hidden;
border: 2px solid transparent;
}
.result-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.result-item.success {
border-color: #52c41a;
}
.result-item.failed {
border-color: #ff4d4f;
}
.result-item .result-name {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.6);
color: #fff;
font-size: 10px;
padding: 4px 6px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.result-item .result-status {
position: absolute;
top: 4px;
right: 4px;
font-size: 14px;
}
/* ========== Responsive ========== */
@media (max-width: 480px) {
.container {
padding: 12px 10px 30px;
}
.header h1 {
font-size: 20px;
}
.folder-section,
.upload-section,
.result-section {
padding: 14px;
border-radius: 10px;
}
.select-area {
padding: 20px 14px;
}
.preview-grid {
grid-template-columns: repeat(auto-fill, minmax(72px, 1fr));
gap: 8px;
}
.result-grid {
grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
gap: 8px;
}
.btn-large {
padding: 12px;
font-size: 15px;
}
/* 移动端始终显示删除按钮 */
.preview-item .remove-btn {
opacity: 1;
}
}
@media (min-width: 481px) and (max-width: 768px) {
.preview-grid {
grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
}
}
/* ========== Scrollbar ========== */
.preview-grid::-webkit-scrollbar,
.file-progress-list::-webkit-scrollbar,
.result-grid::-webkit-scrollbar {
width: 4px;
}
.preview-grid::-webkit-scrollbar-thumb,
.file-progress-list::-webkit-scrollbar-thumb,
.result-grid::-webkit-scrollbar-thumb {
background: #ddd;
border-radius: 2px;
}
/* ========== Loading animation ========== */
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.uploading {
animation: pulse 1.5s ease-in-out infinite;
}

View File

@@ -0,0 +1,413 @@
// ========== 写死的选项数据 ==========
const ALL_CAMPS = [];
for (let i = 13; i <= 26; i++) {
ALL_CAMPS.push(`训练营${i}`);
}
const ALL_CLASSES = [];
for (let i = 1; i <= 25; i++) {
ALL_CLASSES.push(`${i}`);
}
const ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
const MAX_FILE_SIZE_MB = 20;
const MAX_FILES_COUNT = 100;
// ========== 状态管理 ==========
let state = {
selectedCamp: '',
selectedClass: '',
selectedFiles: [], // { file, id, previewUrl }
uploadResults: [], // { file, id, status, filename, reason, previewUrl }
isUploading: false,
};
// ========== DOM 元素 ==========
const $ = (sel) => document.querySelector(sel);
const campSelect = $('#camp-select');
const classSelect = $('#class-select');
const fileInput = $('#file-input');
const uploadSection = $('.upload-section');
const selectArea = $('#select-area');
const previewSection = $('#preview-section');
const previewGrid = $('#preview-grid');
const selectedCount = $('#selected-count');
const btnUpload = $('#btn-upload');
const btnClearAll = $('#btn-clear-all');
const progressSection = $('#progress-section');
const progressText = $('#progress-text');
const progressPercent = $('#progress-percent');
const progressFill = $('#progress-fill');
const fileProgressList = $('#file-progress-list');
const resultSection = $('#result-section');
const resultSummary = $('#result-summary');
const resultGrid = $('#result-grid');
const btnRetry = $('#btn-retry');
const btnNewUpload = $('#btn-new-upload');
// ========== 初始化 ==========
function init() {
loadFolders();
bindEvents();
}
// ========== 文件夹加载(前端写死选项) ==========
function loadFolders() {
campSelect.innerHTML = '<option value="">-- 请选择训练营 --</option>';
ALL_CAMPS.forEach(camp => {
const opt = document.createElement('option');
opt.value = camp;
opt.textContent = camp;
campSelect.appendChild(opt);
});
}
function onCampChange() {
const campName = campSelect.value;
state.selectedCamp = campName;
classSelect.innerHTML = '';
classSelect.disabled = true;
state.selectedClass = '';
if (!campName) {
classSelect.innerHTML = '<option value="">-- 请先选择训练营 --</option>';
return;
}
classSelect.disabled = false;
classSelect.innerHTML = '<option value="">-- 请选择班级 --</option>';
ALL_CLASSES.forEach(cls => {
const opt = document.createElement('option');
opt.value = cls;
opt.textContent = cls;
classSelect.appendChild(opt);
});
}
function onClassChange() {
state.selectedClass = classSelect.value;
}
// ========== 文件选择 ==========
function onFileSelect(e) {
const files = Array.from(e.target.files);
if (!files.length) return;
const remaining = MAX_FILES_COUNT - state.selectedFiles.length;
if (remaining <= 0) {
alert(`最多只能选择 ${MAX_FILES_COUNT} 张图片`);
fileInput.value = '';
return;
}
const filesToAdd = files.slice(0, remaining);
let rejected = 0;
filesToAdd.forEach(file => {
if (file.size > MAX_FILE_SIZE_MB * 1024 * 1024) {
rejected++;
return;
}
const ext = file.name.split('.').pop().toLowerCase();
if (!ALLOWED_EXTENSIONS.includes(ext)) {
rejected++;
return;
}
const id = Date.now() + '_' + Math.random().toString(36).substr(2, 6);
const previewUrl = URL.createObjectURL(file);
state.selectedFiles.push({ file, id, previewUrl });
});
if (rejected > 0) {
alert(`已跳过 ${rejected} 个文件(格式不支持或超过 20MB`);
}
fileInput.value = '';
renderPreview();
}
function removeFile(id) {
const idx = state.selectedFiles.findIndex(f => f.id === id);
if (idx !== -1) {
URL.revokeObjectURL(state.selectedFiles[idx].previewUrl);
state.selectedFiles.splice(idx, 1);
}
renderPreview();
}
function clearAllFiles() {
state.selectedFiles.forEach(f => URL.revokeObjectURL(f.previewUrl));
state.selectedFiles = [];
renderPreview();
}
function renderPreview() {
const count = state.selectedFiles.length;
if (count === 0) {
previewSection.style.display = 'none';
selectArea.style.display = 'block';
return;
}
selectArea.style.display = 'none';
previewSection.style.display = 'block';
selectedCount.textContent = count;
btnUpload.disabled = !state.selectedCamp || !state.selectedClass || state.isUploading;
previewGrid.innerHTML = '';
state.selectedFiles.forEach(item => {
const div = document.createElement('div');
div.className = 'preview-item';
div.innerHTML = `
<img src="${item.previewUrl}" alt="${item.file.name}">
<button class="remove-btn" onclick="removeFile('${item.id}')">×</button>
<div class="file-name">${item.file.name}</div>
`;
previewGrid.appendChild(div);
});
}
// ========== 上传逻辑真实API ==========
function uploadFile(file, campName, className, onProgress) {
return new Promise((resolve) => {
const formData = new FormData();
formData.append('folder', campName);
formData.append('class', className);
formData.append('files', file);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload');
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) {
onProgress(Math.round((e.loaded / e.total) * 100));
}
};
xhr.onload = () => {
try {
const data = JSON.parse(xhr.responseText);
if (xhr.status === 200 && data.uploaded && data.uploaded.length > 0) {
resolve({ type: 'success', filename: data.uploaded[0].filename });
} else if (data.failed && data.failed.length > 0) {
resolve({ type: 'failed', reason: data.failed[0].reason });
} else {
resolve({ type: 'failed', reason: data.error || '上传失败' });
}
} catch (e) {
resolve({ type: 'failed', reason: '服务器响应异常' });
}
};
xhr.onerror = () => {
resolve({ type: 'failed', reason: '网络错误' });
};
xhr.ontimeout = () => {
resolve({ type: 'failed', reason: '请求超时' });
};
xhr.timeout = 120000; // 2分钟超时
xhr.send(formData);
});
}
async function startUpload() {
if (!state.selectedCamp || !state.selectedClass) {
alert('请先选择训练营和班级');
return;
}
if (state.selectedFiles.length === 0) {
alert('请先选择图片');
return;
}
state.isUploading = true;
btnUpload.disabled = true;
btnUpload.textContent = '上传中...';
btnUpload.classList.add('uploading');
// 切换到进度视图
previewSection.style.display = 'none';
resultSection.style.display = 'none';
progressSection.style.display = 'block';
// 初始化进度列表
fileProgressList.innerHTML = '';
state.selectedFiles.forEach(item => {
const div = document.createElement('div');
div.className = 'file-progress-item';
div.id = `progress-${item.id}`;
div.innerHTML = `
<span class="status-icon">⏳</span>
<div class="file-info">
<div class="name">${item.file.name}</div>
<div class="detail">等待上传...</div>
</div>
<div class="mini-progress"><div class="mini-fill" style="width:0%"></div></div>
`;
fileProgressList.appendChild(div);
});
// 逐张上传
let completed = 0;
const total = state.selectedFiles.length;
state.uploadResults = [];
for (const item of state.selectedFiles) {
const el = $(`#progress-${item.id}`);
const icon = el.querySelector('.status-icon');
const detail = el.querySelector('.detail');
const miniFill = el.querySelector('.mini-fill');
// 上传中
icon.textContent = '📤';
detail.textContent = '上传中...';
// 调用真实API
const result = await uploadFile(item.file, state.selectedCamp, state.selectedClass, (percent) => {
miniFill.style.width = `${percent}%`;
});
if (result.type === 'success') {
icon.textContent = '✅';
detail.textContent = result.filename;
el.classList.add('status-success');
miniFill.style.width = '100%';
miniFill.style.background = '#52c41a';
state.uploadResults.push({
file: item.file,
id: item.id,
previewUrl: item.previewUrl,
status: 'success',
filename: result.filename,
});
} else if (result.type === 'failed') {
icon.textContent = '❌';
detail.textContent = `上传失败:${result.reason}`;
el.classList.add('status-failed');
miniFill.style.width = '100%';
miniFill.style.background = '#ff4d4f';
state.uploadResults.push({
file: item.file,
id: item.id,
previewUrl: item.previewUrl,
status: 'failed',
filename: item.file.name,
reason: result.reason,
});
}
completed++;
const percent = Math.round((completed / total) * 100);
progressText.textContent = `上传中... ${completed} / ${total}`;
progressPercent.textContent = `${percent}%`;
progressFill.style.width = `${percent}%`;
}
// 上传完成
state.isUploading = false;
btnUpload.textContent = '开始上传';
btnUpload.classList.remove('uploading');
setTimeout(() => {
progressSection.style.display = 'none';
uploadSection.style.display = 'none';
showResults();
}, 500);
}
// ========== 结果展示 ==========
function showResults() {
resultSection.style.display = 'block';
const successList = state.uploadResults.filter(r => r.status === 'success');
const failedList = state.uploadResults.filter(r => r.status === 'failed');
let summaryHtml = `共上传 <strong>${state.uploadResults.length}</strong> 张图片,`;
summaryHtml += `<span class="success-count">成功 ${successList.length} 张</span>`;
if (failedList.length > 0) {
summaryHtml += `<span class="fail-count">失败 ${failedList.length} 张</span>`;
}
resultSummary.innerHTML = summaryHtml;
btnRetry.style.display = failedList.length > 0 ? 'inline-block' : 'none';
resultGrid.innerHTML = '';
state.uploadResults.forEach(item => {
const div = document.createElement('div');
div.className = `result-item ${item.status}`;
div.innerHTML = `
<img src="${item.previewUrl}" alt="${item.filename}">
<div class="result-name">${item.status === 'success' ? item.filename : item.filename}</div>
<span class="result-status">${item.status === 'success' ? '✅' : '❌'}</span>
`;
resultGrid.appendChild(div);
});
}
function retryFailed() {
const failedItems = state.uploadResults.filter(r => r.status === 'failed');
state.selectedFiles = failedItems.map(item => ({
file: item.file,
id: item.id,
previewUrl: item.previewUrl,
}));
state.uploadResults = [];
resultSection.style.display = 'none';
progressSection.style.display = 'none';
uploadSection.style.display = 'block';
renderPreview();
}
function newUpload() {
state.selectedFiles.forEach(f => URL.revokeObjectURL(f.previewUrl));
state.selectedFiles = [];
state.uploadResults = [];
state.isUploading = false;
resultSection.style.display = 'none';
progressSection.style.display = 'none';
uploadSection.style.display = 'block';
previewSection.style.display = 'none';
selectArea.style.display = 'block';
btnUpload.disabled = true;
btnUpload.textContent = '开始上传';
}
// ========== 事件绑定 ==========
function bindEvents() {
campSelect.addEventListener('change', onCampChange);
classSelect.addEventListener('change', onClassChange);
fileInput.addEventListener('change', onFileSelect);
btnUpload.addEventListener('click', startUpload);
btnClearAll.addEventListener('click', clearAllFiles);
btnRetry.addEventListener('click', retryFailed);
btnNewUpload.addEventListener('click', newUpload);
campSelect.addEventListener('change', () => {
if (state.selectedFiles.length > 0) renderPreview();
});
classSelect.addEventListener('change', () => {
if (state.selectedFiles.length > 0) renderPreview();
});
}
// ========== 启动 ==========
document.addEventListener('DOMContentLoaded', init);

View File

@@ -0,0 +1,88 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>训练营图片上传</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<div class="container">
<!-- 顶部标题 -->
<header class="header">
<h1>📷 训练营图片上传</h1>
<p class="subtitle">选择训练营和班级,上传截图文件</p>
</header>
<!-- 文件夹选择区 -->
<section class="folder-section">
<div class="form-group">
<label for="camp-select">选择训练营</label>
<select id="camp-select">
<option value="">-- 请选择训练营 --</option>
</select>
</div>
<div class="form-group">
<label for="class-select">选择班级</label>
<select id="class-select" disabled>
<option value="">-- 请先选择训练营 --</option>
</select>
</div>
</section>
<!-- 图片选择和上传区 -->
<section class="upload-section">
<div class="select-area" id="select-area">
<div class="select-icon">📁</div>
<p>点击下方按钮选择图片</p>
<p class="hint">支持 JPG / PNG / GIF / WEBP单张不超过 20MB最多 100 张</p>
<button class="btn btn-primary" id="btn-select" onclick="document.getElementById('file-input').click()">
选择图片
</button>
<input type="file" id="file-input" accept="image/jpeg,image/png,image/gif,image/webp" multiple hidden>
</div>
<!-- 已选图片预览 -->
<div class="preview-section" id="preview-section" style="display:none;">
<div class="preview-header">
<span>已选择 <strong id="selected-count">0</strong> 张图片</span>
<button class="btn btn-small btn-danger" id="btn-clear-all">清空全部</button>
</div>
<div class="preview-grid" id="preview-grid"></div>
<button class="btn btn-primary btn-large" id="btn-upload" disabled>
开始上传
</button>
</div>
<!-- 上传进度区 -->
<div class="progress-section" id="progress-section" style="display:none;">
<div class="progress-header">
<span id="progress-text">上传中... 0 / 0</span>
<span id="progress-percent">0%</span>
</div>
<div class="progress-bar">
<div class="progress-fill" id="progress-fill"></div>
</div>
<div class="file-progress-list" id="file-progress-list"></div>
</div>
</section>
<!-- 上传结果区 -->
<section class="result-section" id="result-section" style="display:none;">
<div class="result-header">
<h2>上传结果</h2>
<p id="result-summary"></p>
</div>
<div class="result-grid" id="result-grid"></div>
<button class="btn btn-primary" id="btn-retry" style="display:none;">
重试失败的图片
</button>
<button class="btn btn-secondary" id="btn-new-upload">
继续上传
</button>
</section>
</div>
<script src="/static/js/app.js"></script>
</body>
</html>