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:
@@ -0,0 +1,328 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
分片(断点续传)上传。
|
||||
|
||||
为什么需要:单个 400MB 的 POST 在移动网络/家宽上要跑几分钟到十几分钟,任何一端的
|
||||
读超时(Traefik 60s、手机系统、运营商)都会把整个请求作废,客户端只能从头再传。
|
||||
切片后每片只有几 MB,失败只重传那一片。
|
||||
|
||||
接口(与现有 /api/submit 并存,老客户端不受影响):
|
||||
|
||||
POST /api/upload/init {formId, field, filename, size, chunkSize?}
|
||||
→ {upload_id, chunk_size, expires_in}
|
||||
POST /api/upload/chunk ?upload_id=..&index=.. 原始字节 body
|
||||
→ {ok, index, received, total_received, complete}
|
||||
GET /api/upload/status ?upload_id=..
|
||||
→ {received:[...], missing:[...], complete}
|
||||
POST /api/upload/complete {upload_id}
|
||||
→ {ok, upload_id, size, sha256}
|
||||
|
||||
最后提交时把 fileTokens={"字段名": upload_id, ...} 一起 POST 到 /api/submit,
|
||||
服务端把已拼好的文件挂到提交记录上(不再走 multipart 传文件)。
|
||||
|
||||
存储:data/chunks/<upload_id>/part_<index>,完成后拼成 assembled.bin。
|
||||
过期:默认 24 小时,由 app.py 的定时任务清理。
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from config import DATA_DIR
|
||||
from database import attach_uploaded_file, get_form
|
||||
from utils.helpers import get_client_ip # noqa: F401 (与提交接口一致的客户端 IP 口径)
|
||||
|
||||
bp = Blueprint('chunked', __name__)
|
||||
|
||||
CHUNKS_DIR = os.path.join(os.fspath(DATA_DIR), 'chunks')
|
||||
DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024 # 8MB/片:弱网下单片几十秒,重传代价可接受
|
||||
MAX_CHUNK_SIZE = 32 * 1024 * 1024
|
||||
MAX_CHUNKS = 20000
|
||||
TTL_SECONDS = 24 * 3600
|
||||
|
||||
_UPLOAD_ID_RE = re.compile(r'^[0-9a-f]{32}$')
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 工具函数
|
||||
|
||||
def _upload_dir(upload_id: str) -> str:
|
||||
if not _UPLOAD_ID_RE.match(upload_id or ''):
|
||||
raise ValueError('upload_id 不合法')
|
||||
return os.path.join(CHUNKS_DIR, upload_id)
|
||||
|
||||
|
||||
def _meta_path(upload_id: str) -> str:
|
||||
return os.path.join(_upload_dir(upload_id), 'meta.json')
|
||||
|
||||
|
||||
def _read_meta(upload_id: str) -> dict:
|
||||
path = _meta_path(upload_id)
|
||||
if not os.path.isfile(path):
|
||||
raise FileNotFoundError('上传会话不存在或已过期')
|
||||
with open(path, encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def _write_meta(upload_id: str, meta: dict) -> None:
|
||||
path = _meta_path(upload_id)
|
||||
tmp = path + '.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
json.dump(meta, f, ensure_ascii=False)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def _check_field(form: dict, field_name: str, filename: str, size: int):
|
||||
"""校验字段存在、扩展名允许、体积不超限。返回该字段配置。"""
|
||||
file_fields = [f for f in form.get('fields', []) if f.get('type') == 'file']
|
||||
field = next((f for f in file_fields if f.get('name') == field_name), None)
|
||||
if field is None:
|
||||
raise ValueError(f'表单里没有文件字段 {field_name}')
|
||||
|
||||
ext = (filename.rsplit('.', 1)[-1] if '.' in filename else '').lower()
|
||||
allowed = field.get('allowedExts') or form.get('allowedExts') or []
|
||||
if allowed and ext not in [e.lower() for e in allowed]:
|
||||
raise ValueError(f'不支持的格式: {ext}')
|
||||
|
||||
limit = form.get('maxSize') or 0
|
||||
if limit and size > limit:
|
||||
raise ValueError(f'文件大小超过限制(上限 {limit // 1048576}MB)')
|
||||
return field
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 接口
|
||||
|
||||
@bp.route('/api/upload/init', methods=['POST'])
|
||||
def upload_init():
|
||||
body = request.get_json(silent=True) or {}
|
||||
form_id = (body.get('formId') or '').strip()
|
||||
field_name = (body.get('field') or '').strip()
|
||||
filename = (body.get('filename') or '').strip()
|
||||
try:
|
||||
size = int(body.get('size') or 0)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify(ok=False, message='size 必须是整数'), 400
|
||||
|
||||
if not form_id or not field_name or not filename:
|
||||
return jsonify(ok=False, message='formId / field / filename 必填'), 400
|
||||
if size <= 0:
|
||||
return jsonify(ok=False, message='size 必须大于 0'), 400
|
||||
|
||||
form = get_form(form_id)
|
||||
if not form:
|
||||
return jsonify(ok=False, message='表单配置不存在或已过期'), 400
|
||||
|
||||
try:
|
||||
_check_field(form, field_name, filename, size)
|
||||
except ValueError as e:
|
||||
return jsonify(ok=False, message=str(e)), 400
|
||||
|
||||
chunk_size = int(body.get('chunkSize') or DEFAULT_CHUNK_SIZE)
|
||||
chunk_size = max(256 * 1024, min(chunk_size, MAX_CHUNK_SIZE))
|
||||
total = (size + chunk_size - 1) // chunk_size
|
||||
if total > MAX_CHUNKS:
|
||||
return jsonify(ok=False, message='分片数量过多,请增大 chunkSize'), 400
|
||||
|
||||
upload_id = uuid.uuid4().hex
|
||||
os.makedirs(_upload_dir(upload_id), exist_ok=True)
|
||||
_write_meta(upload_id, {
|
||||
'upload_id': upload_id,
|
||||
'form_id': form_id,
|
||||
'field': field_name,
|
||||
'filename': filename,
|
||||
'size': size,
|
||||
'chunk_size': chunk_size,
|
||||
'total': total,
|
||||
'created': int(time.time()),
|
||||
'ip': request.headers.get('X-Forwarded-For', request.remote_addr or '').split(',')[0].strip(),
|
||||
'complete': False,
|
||||
'sha256': None,
|
||||
})
|
||||
return jsonify(ok=True, upload_id=upload_id, chunk_size=chunk_size,
|
||||
total_chunks=total, expires_in=TTL_SECONDS)
|
||||
|
||||
|
||||
@bp.route('/api/upload/chunk', methods=['POST'])
|
||||
def upload_chunk():
|
||||
upload_id = (request.args.get('upload_id') or '').strip()
|
||||
try:
|
||||
index = int(request.args.get('index'))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify(ok=False, message='index 必须是整数'), 400
|
||||
|
||||
try:
|
||||
meta = _read_meta(upload_id)
|
||||
except ValueError as e:
|
||||
return jsonify(ok=False, message=str(e)), 400
|
||||
except FileNotFoundError as e:
|
||||
return jsonify(ok=False, message=str(e)), 404
|
||||
|
||||
if meta.get('complete'):
|
||||
return jsonify(ok=False, message='该上传已完成,请勿重复分片'), 409
|
||||
if index < 0 or index >= meta['total']:
|
||||
return jsonify(ok=False, message=f'index 越界(0..{meta["total"] - 1})'), 400
|
||||
|
||||
# 单片体积上限:最后一片可能不满
|
||||
expected = min(meta['chunk_size'], meta['size'] - index * meta['chunk_size'])
|
||||
data = request.get_data(cache=False)
|
||||
if len(data) > expected:
|
||||
return jsonify(ok=False, message=f'分片过大({len(data)} > {expected})'), 400
|
||||
if len(data) == 0:
|
||||
return jsonify(ok=False, message='分片为空'), 400
|
||||
|
||||
path = os.path.join(_upload_dir(upload_id), f'part_{index}')
|
||||
tmp = path + '.tmp'
|
||||
with open(tmp, 'wb') as f:
|
||||
f.write(data)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, path) # 幂等:同一片重传直接覆盖
|
||||
|
||||
received = _received_indexes(upload_id, meta['total'])
|
||||
return jsonify(ok=True, index=index, received=len(received),
|
||||
total_received=sum(os.path.getsize(os.path.join(_upload_dir(upload_id), f'part_{i}'))
|
||||
for i in received),
|
||||
complete=len(received) == meta['total'])
|
||||
|
||||
|
||||
def _received_indexes(upload_id: str, total: int) -> list:
|
||||
d = _upload_dir(upload_id)
|
||||
out = []
|
||||
for i in range(total):
|
||||
if os.path.isfile(os.path.join(d, f'part_{i}')):
|
||||
out.append(i)
|
||||
return out
|
||||
|
||||
|
||||
@bp.route('/api/upload/status', methods=['GET'])
|
||||
def upload_status():
|
||||
upload_id = (request.args.get('upload_id') or '').strip()
|
||||
try:
|
||||
meta = _read_meta(upload_id)
|
||||
except ValueError as e:
|
||||
return jsonify(ok=False, message=str(e)), 400
|
||||
except FileNotFoundError as e:
|
||||
return jsonify(ok=False, message=str(e)), 404
|
||||
|
||||
received = _received_indexes(upload_id, meta['total'])
|
||||
missing = [i for i in range(meta['total']) if i not in received]
|
||||
return jsonify(ok=True, upload_id=upload_id, size=meta['size'],
|
||||
chunk_size=meta['chunk_size'], total_chunks=meta['total'],
|
||||
received=received, missing=missing,
|
||||
complete=meta.get('complete', False) or not missing)
|
||||
|
||||
|
||||
@bp.route('/api/upload/complete', methods=['POST'])
|
||||
def upload_complete():
|
||||
body = request.get_json(silent=True) or {}
|
||||
upload_id = (body.get('upload_id') or '').strip()
|
||||
try:
|
||||
meta = _read_meta(upload_id)
|
||||
except ValueError as e:
|
||||
return jsonify(ok=False, message=str(e)), 400
|
||||
except FileNotFoundError as e:
|
||||
return jsonify(ok=False, message=str(e)), 404
|
||||
|
||||
if meta.get('complete'):
|
||||
return jsonify(ok=True, upload_id=upload_id, size=meta['size'],
|
||||
sha256=meta.get('sha256'), already=True)
|
||||
|
||||
received = _received_indexes(upload_id, meta['total'])
|
||||
missing = [i for i in range(meta['total']) if i not in received]
|
||||
if missing:
|
||||
return jsonify(ok=False, message='还有分片未上传', missing=missing[:50],
|
||||
missing_count=len(missing)), 409
|
||||
|
||||
d = _upload_dir(upload_id)
|
||||
assembled = os.path.join(d, 'assembled.bin')
|
||||
tmp = assembled + '.tmp'
|
||||
digest = hashlib.sha256()
|
||||
written = 0
|
||||
try:
|
||||
with open(tmp, 'wb') as out:
|
||||
for i in range(meta['total']):
|
||||
with open(os.path.join(d, f'part_{i}'), 'rb') as part:
|
||||
while True:
|
||||
chunk = part.read(4 * 1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
out.write(chunk)
|
||||
digest.update(chunk)
|
||||
written += len(chunk)
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
except BaseException:
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
if written != meta['size']:
|
||||
os.remove(tmp)
|
||||
return jsonify(ok=False,
|
||||
message=f'合并后大小不符(实际 {written},声明 {meta["size"]})'), 400
|
||||
|
||||
os.replace(tmp, assembled)
|
||||
for i in range(meta['total']): # 合并成功后清掉分片,省磁盘
|
||||
try:
|
||||
os.remove(os.path.join(d, f'part_{i}'))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
meta['complete'] = True
|
||||
meta['sha256'] = digest.hexdigest()
|
||||
meta['completed_at'] = int(time.time())
|
||||
_write_meta(upload_id, meta)
|
||||
return jsonify(ok=True, upload_id=upload_id, size=written, sha256=meta['sha256'])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 供 /api/submit 使用
|
||||
|
||||
def consume_upload(upload_id: str, form_id: str, field_name: str):
|
||||
"""校验并返回待挂载的 assembled 文件路径(不移动,由 attach_uploaded_file 负责)。"""
|
||||
meta = _read_meta(upload_id)
|
||||
if not meta.get('complete'):
|
||||
raise ValueError('分片尚未合并完成')
|
||||
if meta.get('form_id') != form_id:
|
||||
raise ValueError('该上传不属于当前表单')
|
||||
if meta.get('field') != field_name:
|
||||
raise ValueError('该上传不属于当前字段')
|
||||
path = os.path.join(_upload_dir(upload_id), 'assembled.bin')
|
||||
if not os.path.isfile(path):
|
||||
raise ValueError('合并文件丢失,请重新上传')
|
||||
return path, meta
|
||||
|
||||
|
||||
def discard_upload(upload_id: str) -> None:
|
||||
try:
|
||||
shutil.rmtree(_upload_dir(upload_id), ignore_errors=True)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
|
||||
def cleanup_stale_uploads() -> int:
|
||||
"""清理超过 TTL 的分片会话(含未完成和已挂载但遗留的目录)。"""
|
||||
if not os.path.isdir(CHUNKS_DIR):
|
||||
return 0
|
||||
now = time.time()
|
||||
removed = 0
|
||||
for name in os.listdir(CHUNKS_DIR):
|
||||
path = os.path.join(CHUNKS_DIR, name)
|
||||
if not os.path.isdir(path):
|
||||
continue
|
||||
try:
|
||||
age = now - os.path.getmtime(path)
|
||||
except OSError:
|
||||
continue
|
||||
if age > TTL_SECONDS:
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
removed += 1
|
||||
return removed
|
||||
Reference in New Issue
Block a user