图片预览改为服务端派生 WebP 直连,修复大图加载慢
新增 /files/preview:按宽度生成 WebP 并落盘缓存,inline + ETag,原图仅下载时取;前端图片与全屏查看器改用派生直链,不再 fetch 整包转 blob。
This commit is contained in:
@@ -25,6 +25,12 @@ function pvOfficeUrl(rel) {
|
||||
String(rel).split('/').filter(Boolean).map(encodeURIComponent).join('/') + '/';
|
||||
}
|
||||
|
||||
// 图片预览派生地址:服务端按 w 生成并缓存 WebP,<img> 直连可边下边画;原图只留给“下载”。
|
||||
function pvPreviewUrl(rel, w) {
|
||||
return '/api/sessions/' + encodeURIComponent(state.sessionId) +
|
||||
'/files/preview?path=' + encodeURIComponent(rel) + '&w=' + w;
|
||||
}
|
||||
|
||||
function pvKind(name) {
|
||||
const low = String(name).toLowerCase();
|
||||
if (/\.html?$/i.test(low)) return 'html';
|
||||
@@ -36,8 +42,8 @@ function pvKind(name) {
|
||||
}
|
||||
|
||||
// 文件面板「当前目录」里的图片作为一组,供查看器左右滑动切换。
|
||||
// 同组直接用下载直链(<img> 不受 Content-Disposition: attachment 影响),不必逐张取 blob。
|
||||
// 依赖 files.js 的 filesNodeAt / filesCurDir / assetDownloadUrl(同为全局,加载顺序在前)。
|
||||
// 同组直接用预览派生直链(2048px),不必逐张取原图/blob,滑动的预取也不会打满带宽。
|
||||
// 依赖 files.js 的 filesNodeAt / filesCurDir(同为全局,加载顺序在前)。
|
||||
function pvImgGroup(name) {
|
||||
try {
|
||||
if (typeof filesNodeAt !== 'function') return null;
|
||||
@@ -46,7 +52,7 @@ function pvImgGroup(name) {
|
||||
const paths = node.files.map(f => f.filename).filter(p => PV_IMG.test(p));
|
||||
if (paths.length < 2) return null;
|
||||
return {
|
||||
list: paths.map(p => ({ src: assetDownloadUrl(p), alt: p.split('/').pop() })),
|
||||
list: paths.map(p => ({ src: pvPreviewUrl(p, 2048), alt: p.split('/').pop() })),
|
||||
at: paths.indexOf(name),
|
||||
};
|
||||
} catch (_) { return null; }
|
||||
@@ -54,8 +60,9 @@ function pvImgGroup(name) {
|
||||
|
||||
// 刷新/新窗口两个钮对**所有**预览类型统一开放:
|
||||
// refresh → pvState.reload(各类型都注入「按同一路径重开」,与地址条回车同一条路)
|
||||
// popup → pvState.url(office=预览网关;文本/HTML/图片/PDF=blob URL;不支持的类型=下载地址)
|
||||
// 服务端文件响应一律是 attachment,直接导航只会触发下载,所以能用 blob 的一律走 blob。
|
||||
// popup → pvState.url(office=预览网关;图片=inline 预览直链;文本/HTML/PDF=blob URL;
|
||||
// 不支持的类型=下载地址)
|
||||
// 下载接口是 attachment,直接导航只会触发下载;图片走 /files/preview(inline)可直接开新窗口。
|
||||
function pvToolbar(o) {
|
||||
document.getElementById('pv-refresh').classList.toggle('hidden', !o.refresh);
|
||||
document.getElementById('pv-popup').classList.toggle('hidden', !o.popup);
|
||||
@@ -223,6 +230,30 @@ async function openFilePreview(name, sizeText) {
|
||||
show(pvInfoNode(name, sizeText, hint), tbAll);
|
||||
return;
|
||||
}
|
||||
// 图片走服务端派生预览:<img> 直连边下边画,不再 fetch 整包转 blob;原图只在“下载”时取。
|
||||
// SVG 保留原路径(移动端还要展示源码),其余图片统一交给 /files/preview。
|
||||
if (kind === 'img' && !/\.svg$/i.test(name)) {
|
||||
const alt = String(name).split('/').pop();
|
||||
const g = pvImgGroup(name);
|
||||
if (desk) {
|
||||
const im = document.createElement('img');
|
||||
im.className = 'pv-img'; im.alt = String(name); im.decoding = 'async';
|
||||
// 面板宽度约半屏,交给浏览器按 DPR 选 640/1280/2048,手机不会去拉大图
|
||||
im.sizes = '(min-width: 960px) 50vw, 100vw';
|
||||
im.srcset = [640, 1280, 2048].map(w => pvPreviewUrl(name, w) + ' ' + w + 'w').join(',');
|
||||
const url = pvPreviewUrl(name, 2048);
|
||||
im.src = url;
|
||||
im.addEventListener('click', () => openImageViewer(url, alt, g && g.list, g && g.at));
|
||||
im.addEventListener('error', () => {
|
||||
if (my !== pvSeq) return;
|
||||
show(pvInfoNode(name, sizeText, '图片读取失败:文件可能已被删除,或格式无法解码。'), tbAll);
|
||||
});
|
||||
show(im, Object.assign({}, tbAll, { url }));
|
||||
} else {
|
||||
openImageViewer(pvPreviewUrl(name, 2048), alt, g && g.list, g && g.at);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let r;
|
||||
try {
|
||||
r = await fetch('/api/sessions/' + state.sessionId + '/files/download?path=' + encodeURIComponent(name));
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// 文件管理 API:上传 / 列表 / 下载 / 删除
|
||||
// 文件管理 API:上传 / 列表 / 下载 / 预览 / 删除
|
||||
const express = require('express');
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const multer = require('multer');
|
||||
@@ -146,6 +147,74 @@ router.get('/:id/files/download', serveDownload);
|
||||
// 供解析不了 Content-Disposition 的下载器兜底;path 参数与验签逻辑完全一致。
|
||||
router.get('/:id/files/download-name/*', serveDownload);
|
||||
|
||||
// ---------- 图片预览派生图(inline,供 <img> 直连;与下载接口的 attachment/no-store 语义分开) ----------
|
||||
// 大图慢的三层原因:整包 fetch 完才渲染、每次都要重下、把原始像素丢给浏览器解码。
|
||||
// 这里按宽度用 sharp 生成 WebP 落盘缓存,前端 <img> 直连即可边下边画;原图只留给“下载”。
|
||||
const PREVIEW_IMG_RE = /\.(png|jpe?g|gif|webp|svg|bmp|avif|ico)$/i;
|
||||
const PREVIEW_WIDTHS = new Set([320, 640, 960, 1280, 1600, 2048]);
|
||||
let sharp = null;
|
||||
try { sharp = require('sharp'); } catch (_) { /* 未安装 sharp 时整条路由降级为原图直出 */ }
|
||||
|
||||
// 预览响应不能带 Content-Disposition: attachment;.imgcache 是点目录,sendFile 需显式放行。
|
||||
function sendInline(res, abs) {
|
||||
res.setHeader('Cache-Control', 'private, max-age=0, must-revalidate');
|
||||
res.sendFile(abs, { cacheControl: false, dotfiles: 'allow', etag: true, lastModified: true });
|
||||
}
|
||||
|
||||
router.get('/:id/files/preview', async function (req, res) {
|
||||
try {
|
||||
const rel = String(req.query.path || '');
|
||||
if (!rel) return res.status(400).json({ error: '缺少 path 参数' });
|
||||
if (!PREVIEW_IMG_RE.test(rel)) return res.status(400).json({ error: '不是图片' });
|
||||
const w = PREVIEW_WIDTHS.has(Number(req.query.w)) ? Number(req.query.w) : 1600;
|
||||
const taskDir = engine.taskDirOf(req.params.id);
|
||||
const abs = resolveInTask(taskDir, rel);
|
||||
const st = fs.statSync(abs);
|
||||
if (!st.isFile()) return res.status(400).json({ error: '不是文件' });
|
||||
|
||||
// SVG 是矢量;GIF 可能在预览里要保留动画;没有 sharp 时只能原图直出。
|
||||
if (/\.svg$/i.test(rel) || /\.gif$/i.test(rel) || !sharp) {
|
||||
return sendInline(res, abs);
|
||||
}
|
||||
|
||||
// 缓存 key 带 size+mtime:文件被 AI 覆盖后自动失效,不需要额外的清理逻辑。
|
||||
const key = crypto.createHash('sha1')
|
||||
.update(rel + '|' + st.size + '|' + st.mtimeMs + '|' + w)
|
||||
.digest('hex');
|
||||
const outDir = path.join(path.resolve(taskDir), '.imgcache', 'preview');
|
||||
const out = path.join(outDir, key + '.webp');
|
||||
if (!fs.existsSync(out)) {
|
||||
// sharp 默认只取动图首帧,直接给原图避免“预览不动了”。metadata 只读文件头,不解码像素。
|
||||
let meta = null;
|
||||
try { meta = await sharp(abs).metadata(); } catch (_) { /* 交给下面原图兜底 */ }
|
||||
if (meta && meta.pages && meta.pages > 1) return sendInline(res, abs);
|
||||
|
||||
// 小文件不一定像素少(高压缩的大尺寸图仍解码很慢):体积与像素都小才直出原图,
|
||||
// 避免“压缩后反而更大”,也避免把 24MP 的 200KB 图原样丢给低端机解码。
|
||||
const px = meta && meta.width && meta.height ? meta.width * meta.height : 0;
|
||||
if (st.size <= 256 * 1024 && (!px || px <= 2 * 1000 * 1000)) return sendInline(res, abs);
|
||||
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
// 随机临时名 + rename:并发请求不会读到半截文件,也不互相覆盖。
|
||||
const tmp = out + '.' + crypto.randomBytes(4).toString('hex') + '.tmp.webp';
|
||||
try {
|
||||
await sharp(abs, { limitInputPixels: 80 * 1000 * 1000 })
|
||||
.rotate()
|
||||
.resize({ width: w, height: w, fit: 'inside', withoutEnlargement: true })
|
||||
.webp({ quality: 85 })
|
||||
.toFile(tmp);
|
||||
fs.renameSync(tmp, out);
|
||||
} catch (err) {
|
||||
try { fs.unlinkSync(tmp); } catch (_) {}
|
||||
return sendInline(res, abs); // 解码失败/格式不支持 → 原图兜底
|
||||
}
|
||||
}
|
||||
sendInline(res, out);
|
||||
} catch (err) {
|
||||
res.status(404).json({ error: '文件不存在' });
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- 打包下载(选中项含文件夹时,后端把整个选择打成 zip 流式返回) ----------
|
||||
// 纯 Node 实现(STORE 不压缩 + 手拼 zip 结构):任务目录里多是媒体/生成产物,
|
||||
// 压缩收益低;两遍读文件(先算 CRC 再磁盘流发送),内存占用与总大小无关。
|
||||
|
||||
Reference in New Issue
Block a user