diff --git a/templates/index.html b/templates/index.html
index 06b6479..27e0ebc 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -4135,6 +4135,94 @@
function umShowError(msg, sourceEl = document.getElementById('submitBtn')) { UMC.error(msg, sourceEl); }
function closeUploadModal() { UMC.close(); }
+ /* ===== 大文件分片上传(弱网断点续传) =====
+ 小文件(<=4MB)仍走原来的单包 multipart,行为不变;
+ 大文件切成 8MB 分片,每片失败自动退避重试,最后把 upload_id 挂到提交里。 */
+ const CHUNK_THRESHOLD = 4 * 1024 * 1024;
+ const CHUNK_SIZE = 8 * 1024 * 1024;
+ const CHUNK_RETRIES = 5;
+
+ function postJSON(url, body) {
+ return fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body)
+ }).then(async (r) => ({ status: r.status, data: await r.json().catch(() => ({})) }));
+ }
+
+ function putChunk(uploadId, index, blob, onProgress) {
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open('POST', `/api/upload/chunk?upload_id=${encodeURIComponent(uploadId)}&index=${index}`);
+ xhr.setRequestHeader('Content-Type', 'application/octet-stream');
+ xhr.upload.onprogress = (e) => { if (e.lengthComputable && onProgress) onProgress(e.loaded); };
+ xhr.onload = () => {
+ if (xhr.status === 200) {
+ try { resolve(JSON.parse(xhr.responseText || '{}')); } catch (e) { resolve({}); }
+ } else {
+ reject(new Error(`分片 ${index + 1} 上传失败(HTTP ${xhr.status})`));
+ }
+ };
+ xhr.onerror = () => reject(new Error(`分片 ${index + 1} 网络错误`));
+ xhr.ontimeout = () => reject(new Error(`分片 ${index + 1} 超时`));
+ xhr.send(blob);
+ });
+ }
+
+ async function uploadFileChunked(file, formId, fieldName, onProgress) {
+ const init = await postJSON('/api/upload/init', {
+ formId, field: fieldName, filename: file.name, size: file.size, chunkSize: CHUNK_SIZE
+ });
+ if (!init.data || !init.data.ok) throw new Error((init.data && init.data.message) || '上传初始化失败');
+
+ const uploadId = init.data.upload_id;
+ const chunkSize = init.data.chunk_size || CHUNK_SIZE;
+ const total = init.data.total_chunks || Math.ceil(file.size / chunkSize);
+
+ let done = 0;
+ for (let i = 0; i < total; i++) {
+ const blob = file.slice(i * chunkSize, Math.min((i + 1) * chunkSize, file.size));
+ let attempt = 0;
+ for (;;) {
+ try {
+ await putChunk(uploadId, i, blob, (loaded) => {
+ if (onProgress) onProgress(done + Math.min(loaded, blob.size));
+ });
+ break;
+ } catch (err) {
+ attempt += 1;
+ if (attempt > CHUNK_RETRIES) {
+ throw new Error(`${file.name} 第 ${i + 1}/${total} 片重试 ${CHUNK_RETRIES} 次仍失败,请检查网络后重试`);
+ }
+ await new Promise((r) => setTimeout(r, Math.min(1000 * attempt, 8000)));
+ }
+ }
+ done += blob.size;
+ if (onProgress) onProgress(done);
+ }
+
+ const comp = await postJSON('/api/upload/complete', { upload_id: uploadId });
+ if (!comp.data || !comp.data.ok) throw new Error((comp.data && comp.data.message) || '分片合并失败');
+ return uploadId;
+ }
+
+ async function collectPickedFiles() {
+ const map = {};
+ for (const field of inputFields()) {
+ if (field.type !== 'file') continue;
+ const input = document.querySelector(`[name="${field.name}"]`);
+ if (input && input.files && input.files[0]) { map[field.name] = input.files[0]; continue; }
+ const stored = storageManager.files.find((f) => f.fieldName === field.name);
+ if (stored) {
+ try {
+ const got = await storageManager.getFile(stored.id);
+ if (got && got.file) map[field.name] = got.file;
+ } catch (e) { /* 读不出来当作没选 */ }
+ }
+ }
+ return map;
+ }
+
function formatFileSize(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
@@ -4258,6 +4346,9 @@
if (verifyTail === null) return; // 用户取消
}
+ const submitFormId = window.location.pathname.slice(1) || 'default';
+ const pickedFiles = await collectPickedFiles();
+
const formData = new FormData();
formData.append('studentId', tail);
formData.append('formId', window.location.pathname.slice(1) || 'default');
@@ -4278,20 +4369,11 @@
}
}
} else if (field.type === 'file') {
- const input = document.querySelector(`[name="${field.name}"]`);
- if (input && input.files[0]) {
- formData.append(field.name, input.files[0]);
- } else {
- // 尝试从 IndexedDB 获取文件
- const storedFile = storageManager.files.find(f => f.fieldName === field.name);
- if (storedFile) {
- storageManager.getFile(storedFile.id).then(fileData => {
- if (fileData && fileData.file) {
- formData.append(field.name, fileData.file);
- }
- });
- }
- }
+ const picked = pickedFiles[field.name];
+ if (!picked) return;
+ // 大文件不进 FormData:稍后分片上传,用 fileTokens 挂载
+ if (picked.size > CHUNK_THRESHOLD) return;
+ formData.append(field.name, picked);
} else {
const input = document.querySelector(`[name="${field.name}"]`);
if (!input) return;
@@ -4332,6 +4414,44 @@
// 展开上传进度卡片(接管原按钮位置)
umOpenProgress();
+ // ===== 大文件先分片上传,成功后把 upload_id 作为 fileTokens 一起提交 =====
+ const bigFiles = Object.entries(pickedFiles).filter(([, f]) => f && f.size > CHUNK_THRESHOLD);
+ if (bigFiles.length) {
+ const totalBytes = bigFiles.reduce((sum, [, f]) => sum + f.size, 0);
+ const fileTokens = {};
+ let uploadedBefore = 0;
+ let lastTick = Date.now();
+ let lastBytes = 0;
+
+ try {
+ for (const [fieldName, file] of bigFiles) {
+ const uploadId = await uploadFileChunked(file, submitFormId, fieldName, (loadedInFile) => {
+ const overall = uploadedBefore + loadedInFile;
+ const now = Date.now();
+ const dt = (now - lastTick) / 1000;
+ if (dt < 0.25 && overall < totalBytes) return;
+ const speed = dt > 0 ? (overall - lastBytes) / dt / 1024 / 1024 : 0;
+ lastTick = now;
+ lastBytes = overall;
+ const remain = speed > 0 ? (totalBytes - overall) / (speed * 1024 * 1024) : 0;
+ umUpdateProgress({
+ percent: Math.round((overall / totalBytes) * 100),
+ text: `${speed.toFixed(2)} MB/s · ${formatFileSize(overall)} / ${formatFileSize(totalBytes)} · 剩余 ${formatTime(remain)}(分片上传,可断点续传)`
+ });
+ });
+ fileTokens[fieldName] = uploadId;
+ uploadedBefore += file.size;
+ }
+ formData.append('fileTokens', JSON.stringify(fileTokens));
+ } catch (err) {
+ console.error('分片上传失败:', err);
+ submitBtn.disabled = false;
+ submitBtn.classList.remove('opacity-90', 'cursor-not-allowed');
+ umShowError(err.message || '文件上传失败,请重试');
+ return;
+ }
+ }
+
const xhr = new XMLHttpRequest();
let startTime = Date.now(), lastTime = startTime, lastLoaded = 0;