feat(upload): 分片断点续传 + 前端静态资源去 CDN 化

1) 分片上传(routes/chunked.py)
   - POST /api/upload/init  建会话,校验表单/字段/扩展名/体积
   - POST /api/upload/chunk 单片上传,幂等可重传,http body 直写磁盘
   - GET  /api/upload/status 查询已收分片
   - POST /api/upload/complete 按序合并 + sha256 校验 + 清理分片
   - /api/submit 新增 field fileTokens 挂载已上传文件(零拷贝 os.replace)
   - 过期会话(24h)由定时任务清理

2) 弱网下的样式可靠性
   - Tailwind Play CDN / GSAP 改为本地自托管(static/js/vendor/)
   - vendor 资源 1 年 immutable 缓存,自家 css/js 1 小时
   - CSS link 失败自动带 ?r= 重试一次
   - status 页加关键内联样式兜底,极端情况下仍可读

3) 大文件落盘沿用流式写入(无 400MB 内存峰值)
This commit is contained in:
zzy
2026-11-13 12:06:32 +08:00
parent 92dedc38e7
commit 84f8516c37
20 changed files with 614 additions and 59 deletions
+52
View File
@@ -1261,6 +1261,58 @@ def save_file_stream(form_id, file_storage, filename, original_name=None, mime_t
return file_id
def attach_uploaded_file(form_id, src_path, filename, original_name=None, mime_type=None,
field_name=None, submission_id=None):
"""把已经上传并合并好的文件(分片上传的产物)挂到 files 表。
与 save_file_stream 的区别:内容已经在磁盘上,这里只做登记 + 原子移动,
不再复制一遍,所以 400MB 也能瞬间完成。
"""
size = os.path.getsize(src_path)
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"INSERT INTO files "
"(form_id, submission_id, filename, original_name, file_size, mime_type, "
" file_data, uploaded_at, field_name) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
form_id,
submission_id,
filename,
original_name,
size,
mime_type,
b"",
datetime.now().isoformat(),
field_name,
),
)
file_id = cursor.lastrowid
rel_path = f"{form_id}/{file_id}.bin"
abs_path = _disk_path(rel_path)
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
try:
# 同一文件系统内 os.replace 是原子且零拷贝;跨设备退化为复制
try:
os.replace(src_path, abs_path)
except OSError:
import shutil
shutil.copyfileobj(open(src_path, 'rb'), open(abs_path, 'wb'), 4 * 1024 * 1024)
os.remove(src_path)
except BaseException:
try:
os.remove(abs_path)
except OSError:
pass
cursor.execute("DELETE FROM files WHERE id = ?", (file_id,))
raise
cursor.execute("UPDATE files SET file_path = ? WHERE id = ?", (rel_path, file_id))
return file_id
def get_file(file_id):
"""获取单个文件(file_data 从磁盘读取)"""
with get_db_connection() as conn: