From ec70b10c082cac96e04f88a5fbf11cb3fc8710b8 Mon Sep 17 00:00:00 2001 From: kicer Date: Thu, 22 Oct 2026 19:25:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=8B=96=E6=8B=BD=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E5=88=B0=E9=A1=B5=E9=9D=A2=E7=9B=B4=E6=8E=A5=E4=B8=8A?= =?UTF-8?q?=E4=BC=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/server/public/css/style.css | 29 ++++++++ app/server/public/index.html | 8 ++ app/server/public/js/files.js | 125 ++++++++++++++++++++++++++++---- docs/upload.md | 59 +++++++++++++++ 4 files changed, 207 insertions(+), 14 deletions(-) create mode 100644 docs/upload.md diff --git a/app/server/public/css/style.css b/app/server/public/css/style.css index 11e65df..bf6e8d9 100644 --- a/app/server/public/css/style.css +++ b/app/server/public/css/style.css @@ -1429,3 +1429,32 @@ body.pv-resizing #pv-pane iframe { pointer-events: none; } .send-btn .stop-sq { display: none; width: 11px; height: 11px; border-radius: 2px; background: #fff; } .send-btn[data-state="stop"] > svg { display: none; } .send-btn[data-state="stop"] .stop-sq { display: block; } + +/* ================= 拖拽上传提示层 ================= */ +/* window 级 dragenter/dragover 期间显示。pointer-events:none 保证遮罩不抢 drop 目标, + drop 仍由 window 监听器接管(见 js/files.js)。 + 视觉沿用站内弹窗语言:与 .modal-overlay 同一底色,白底卡片 + 16px 圆角 + 投影, + 图标用品牌蓝的浅色圆底,虚线框只作为「可投放」的轻提示。 */ +#drop-overlay { + position: fixed; inset: 0; z-index: 190; + display: flex; align-items: center; justify-content: center; + background: rgba(20, 25, 50, 0.45); + pointer-events: none; + animation: drop-overlay-in .14s ease-out; +} +#drop-overlay .drop-hint { + display: flex; flex-direction: column; align-items: center; gap: 12px; + padding: 24px 36px; + max-width: 80vw; text-align: center; + border: 1.5px dashed rgba(57, 100, 254, 0.32); + border-radius: 16px; + background: var(--page); color: var(--ink); + font-size: 15px; font-weight: 600; + box-shadow: 0 12px 32px rgba(15, 17, 21, 0.18); +} +#drop-overlay .drop-hint .ic { + width: 50px; height: 50px; padding: 12px; + border-radius: 50%; + background: var(--active-soft); color: var(--active); +} +@keyframes drop-overlay-in { from { opacity: 0; } to { opacity: 1; } } diff --git a/app/server/public/index.html b/app/server/public/index.html index 40813bc..5f7c4f4 100644 --- a/app/server/public/index.html +++ b/app/server/public/index.html @@ -480,6 +480,14 @@ + + + diff --git a/app/server/public/js/files.js b/app/server/public/js/files.js index 53f52ec..d06985b 100644 --- a/app/server/public/js/files.js +++ b/app/server/public/js/files.js @@ -815,6 +815,12 @@ card.dataset.done = '1'; // 仅成功上传的卡片参与发送时的告知行 closeBtn.classList.remove('hidden'); }, + // 服务端重名会加 -1/-2:告知行必须用真实落盘名,否则模型读不到/读到旧文件 + rename(name) { + card.dataset.name = name; + const el = card.querySelector('.up-name'); + if (el) { el.textContent = name; el.title = name; } + }, fail() { card.classList.add('err'); mask.innerHTML = '上传失败'; @@ -830,12 +836,10 @@ // 文件选择统一入口:先逐文件预处理(大图压缩询问/大文件确认,X或遮罩=放弃该文件), // 只要还剩至少一个待传文件才自动建档(welcome 无会话时)并走即传路径(多文件并行上传+总进度条+逐卡进度); - // 全部放弃或取消选择都不上传、不新建会话。 - $('file-input').addEventListener('change', async e => { - const input = e.target; - const files = Array.prototype.slice.call(input.files || []); // 先快照再清空,FileList 是实时的 - input.value = ''; - if (!files.length) return; + // 全部放弃或取消选择都不上传、不新建会话。拖拽 drop 也走这里。 + // 并发批次共用一个总进度条:各自登记 {loaded,total},绘制时求和,避免后一批把前一批的进度冲掉。 + const uploadBatches = new Set(); + async function uploadFilesNow(files) { // 逐个串行预处理(模态弹窗不能并行) const ready = []; for (const f of files) { @@ -855,11 +859,13 @@ const cards = ready.map(f => addUploadCard(f)); // ---- 并行上传 + 实时进度 ---- const progWrap = $('fp-progress'), progBar = $('fp-progress-bar'), progPct = $('fp-progress-pct'); - const tot = ready.reduce((s, f) => s + f.size, 0); - const loaded = { v: 0 }; // 所有文件已上传字节总和 + const batch = { loaded: 0, total: ready.reduce((s, f) => s + f.size, 0) }; + uploadBatches.add(batch); let done = 0, errCount = 0; function paintProg() { - const pct = tot ? Math.min(100, Math.round(loaded.v / tot * 100)) : 0; + let loaded = 0, total = 0; + uploadBatches.forEach(b => { loaded += b.loaded; total += b.total; }); + const pct = total ? Math.min(100, Math.round(loaded / total * 100)) : 0; progBar.style.width = pct + '%'; progPct.textContent = pct + '%'; } @@ -874,29 +880,120 @@ xhr.upload.onprogress = function (ev) { if (!ev.lengthComputable) return; // ev.loaded 是本文件累计已发字节,汇总时取本次增量避免多计 - loaded.v += ev.loaded - lastLoaded; + batch.loaded += ev.loaded - lastLoaded; lastLoaded = ev.loaded; paintProg(); card.setPct(ev.loaded / ev.total * 100); }; xhr.onload = function () { - if (xhr.status === 200) { done++; card.done(); } else { errCount++; card.fail(); } + if (xhr.status === 200) { + done++; + try { + const u = (JSON.parse(xhr.responseText || '{}').uploaded || [])[0]; + if (u && u.filename) card.rename(u.filename); + } catch (_) { /* 响应体异常不影响上传成功态 */ } + card.done(); + } else { errCount++; card.fail(); } // 终态补齐(可能没收到最后一帧 100%) - if (lastLoaded < f.size) { loaded.v += f.size - lastLoaded; paintProg(); } + if (lastLoaded < f.size) { batch.loaded += f.size - lastLoaded; paintProg(); } resolve(); }; xhr.onerror = function () { errCount++; card.fail(); resolve(); }; xhr.send(fd); })); await Promise.all(tasks); + if (batch.loaded < batch.total) batch.loaded = batch.total; + uploadBatches.delete(batch); paintProg(); // 全部成功不再弹提示(卡片已完成态即反馈);有失败才提醒 if (errCount) toast('已上传 ' + done + ' 个,失败 ' + errCount + ' 个'); loadFiles(); - // 1.2s 后收起进度条 - setTimeout(() => { progWrap.classList.add('hidden'); progBar.style.width = '0%'; }, 1200); + // 1.2s 后收起进度条(还有别的批次在传就不收) + setTimeout(() => { + if (uploadBatches.size) return; + progWrap.classList.add('hidden'); progBar.style.width = '0%'; + }, 1200); + } + + $('file-input').addEventListener('change', e => { + const input = e.target; + const files = Array.prototype.slice.call(input.files || []); // 先快照再清空,FileList 是实时的 + input.value = ''; + if (files.length) uploadFilesNow(files).catch(er => toast('上传失败:' + (er && er.message || er))); }); + // ---------- 拖拽文件到页面即上传(仅桌面浏览器,触屏没有 drag 事件) ---------- + // 必须挂在 window 上:文件落到输入框/面板/抽屉等任何位置,若没有 drop 处理, + // 浏览器默认行为是导航去打开它,当前草稿和正在流式的回合会一起丢失。 + function pickDroppedFiles(dt) { + // dataTransfer 只在事件回调内有效,这里同步取完;目录在 files 里是 0 字节条目,必须跳过 + const items = dt.items ? Array.prototype.slice.call(dt.items) : []; + if (!items.length) return { files: Array.prototype.slice.call(dt.files || []), dirs: 0 }; + const files = []; + let dirs = 0; + for (const it of items) { + if (it.kind !== 'file') continue; + let entry = null; + try { entry = it.webkitGetAsEntry && it.webkitGetAsEntry(); } catch (_) {} + if (entry && entry.isDirectory) { dirs++; continue; } + const f = it.getAsFile(); + if (f) files.push(f); + } + return { files, dirs }; + } + (function bindDropUpload() { + const overlay = $('drop-overlay'); + if (!overlay) return; + let depth = 0, resetTimer = 0; + // 拖动页面内选中的文字也会触发 dragenter,只认带 Files 的拖拽 + function hasFiles(e) { + const types = e.dataTransfer && e.dataTransfer.types; + return !!types && Array.prototype.indexOf.call(types, 'Files') !== -1; + } + function show() { + clearTimeout(resetTimer); + depth = 1; + overlay.classList.remove('hidden'); + } + function reset() { + depth = 0; + clearTimeout(resetTimer); + overlay.classList.add('hidden'); + } + window.addEventListener('dragenter', e => { + if (!hasFiles(e)) return; + e.preventDefault(); // 旧版 Chrome/Safari 需要它才让区域接受拖放 + if (!depth) depth = 1; + clearTimeout(resetTimer); + overlay.classList.remove('hidden'); + }); + window.addEventListener('dragover', e => { + if (!hasFiles(e)) return; + e.preventDefault(); // 缺这一步 drop 永远不会触发 + e.dataTransfer.dropEffect = 'copy'; + if (overlay.classList.contains('hidden')) show(); + }); + window.addEventListener('dragleave', e => { + if (!hasFiles(e)) return; + // 拖出窗口时浏览器不保证再配对一次 dragenter,relatedTarget 为 null 直接收干净 + if (!e.relatedTarget) { reset(); return; } + depth = Math.max(0, depth - 1); + if (depth) return; + resetTimer = setTimeout(reset, 150); + }); + window.addEventListener('dragend', reset); + window.addEventListener('drop', e => { + if (!hasFiles(e)) return; + e.preventDefault(); // 阻止浏览器默认的“打开文件” + reset(); + const picked = pickDroppedFiles(e.dataTransfer); + if (picked.files.length) { + uploadFilesNow(picked.files).catch(er => toast('上传失败:' + (er && er.message || er))); + } + if (picked.dirs) toast('暂不支持拖入文件夹' + (picked.files.length ? ',已忽略' : '')); + }); + })(); + function renderAttachChips() { const row = $('attach-chips'); diff --git a/docs/upload.md b/docs/upload.md new file mode 100644 index 0000000..b74c393 --- /dev/null +++ b/docs/upload.md @@ -0,0 +1,59 @@ +# 文件上传(选择器 / 拖拽) + +前端上传只有一个落点:`app/server/public/js/files.js` 的 `uploadFilesNow(files)`。 +文件选择器和拖拽 drop 都只负责凑出 `File[]`,之后的大图压缩询问、大文件确认、 +自动建档、逐卡进度、上传与刷新文件面板全部共用同一条链路。 + +## 入口 + +| 入口 | 位置 | 说明 | +|---|---|---| +| 回形针按钮 / 面板上传图标 | `#file-input` 的 `change` | 选中后快照 `input.files` → `uploadFilesNow` | +| 拖拽文件到页面任意位置 | `window` 的 `drop` | 从 `dataTransfer` 同步取 `File[]` → `uploadFilesNow` | + +发布时 `send()` 会把已成功卡片的 `dataset.name` 拼成「用户上传了文件:…」告知行; +卡片名以服务端返回的 `uploaded[].filename` 为准(重名时后端会加 `-1`/`-2`)。 + +## 拖拽实现要点 + +- **监听在 `window` 上**,不是某个 dropZone。文件落到输入框、文件面板、抽屉上时, + 没有处理的 `drop` 会让浏览器导航去打开该文件,当前草稿和正在流式的回合都会丢。 +- **只认带 `Files` 的拖拽**:拖动页面内选中的文字同样触发 `dragenter`,不判断会误弹遮罩。 +- `dragover` 必须 `preventDefault()`,否则 `drop` 不触发;同时设 `dropEffect = 'copy'`。 +- 遮罩 `#drop-overlay` 是 `pointer-events: none` 的固定层,不参与命中测试,drop 仍由 window 接管。 +- `dragenter` / `dragleave` 在子元素间移动会成对冒泡到 window,用 150ms 兜底定时器收尾; + `relatedTarget === null`(拖出窗口)直接收干净。 +- **不支持拖入目录**:目录在 `dataTransfer.files` 里是 0 字节条目,直接传会落一个空文件。 + 实现用 `webkitGetAsEntry().isDirectory` 识别并跳过,有文件时提示「暂不支持拖入文件夹,已忽略」。 +- 触屏设备没有 drag 事件,遮罩只在真实拖拽时出现,不影响移动端布局。 +- 并发批次(上一次还在传又拖入一批)共用一个总进度条:各批登记 `{loaded,total}`, + 绘制时求和,最后一批结束后才收起。 + +## 后端约束(前端已对齐) + +- 单文件硬限 50MB(`routes/files.js` 的 `multer.limits.filesize`),超限在预处理阶段直接拒掉。 +- 大于 `upload.confirm_size_mb`(默认 10MB)先二次确认;大图大于 + `upload.image_compress_threshold_kb`(默认 1536KB)走本地 canvas 压缩询问。 +- 每个文件一个 XHR 请求,所以 `upload.array('files', 10)` 的上限不构成瓶颈。 +- 落盘名经 `sanitizeName` 清洗,重名自动追加序号;前端把响应里的真实文件名回写到卡片, + 避免告知行指向同名的旧文件。 + +## 已知限制 + +- 一次拖入多张大图时,`prepareUploadFile` 会逐张弹压缩确认(串行,不做批量合并)。 +- 拖拽期间会立刻 `ensureSession()` 建档(与回形针一致),即使用户随后放弃上传; + 全部文件被放弃时不会建档。 + +## 未实现:长文本粘贴转文件 + +设计结论留档,便于后续接上同一条链路: + +- 只监听 `#msg-input` 的 `paste`,不挂 `document`(避免劫持搜索框等输入)。 +- 文本超过阈值(字符数,建议默认 2000)时 `preventDefault()`,用 + `new File([原始文本], 'pasted-text-<时间戳>.txt', { type: 'text/plain' })` 构造附件。 + 阈值判断用 trim 后长度,写入必须用原始文本(保留首尾空白与行尾)。 +- 剪贴板同时有文件与文本时,文本超阈值优先转 txt(保留内容),非图片文件一并上传; + 文本很短且仅有截图时,文本走默认粘贴、图片作为附件上传。 +- 建议延迟到发送时上传(存进 `state.attachments`,不提前建会话),需要同步放宽 + `stream.js` 的 `send()`:允许只有附件时发送、告知行合并挂起附件、标题取原文前缀。 +- 上传失败必须把原始文本回填输入框(追加而非覆盖)。