fix(knowledgeBase): 知识库下载文件命名不对
This commit is contained in:
1 parent
dabf140e41
commit
a768eb9024
13 files changed
+299
-28
No files matched your search
@@ -1,12 +1,14 @@
|
||||
/**
|
||||
* features/kb/api/kb.api.ts
|
||||
* 用途:知识库 HTTP API 封装。
|
||||
* 依赖:auth、requestJson/BusinessError、vue-i18n(错误 fallback 文案)。
|
||||
* 依赖:auth、requestJson/BusinessError、vue-i18n(错误 fallback 文案)、shared/utils/download。
|
||||
* 逻辑:KbWorkspace / composables 调用;失败时优先保留 BusinessError.message,否则回退本地化 fallback。
|
||||
* 源文件下载走 ?download=1,文件名由 Content-Disposition filename* 或调用方 source_file_name 决定。
|
||||
*/
|
||||
import i18n from '@/i18n';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { parseContentDispositionFilename } from '@/shared/utils/download';
|
||||
|
||||
const kbT = (key: string) => String(i18n.global.t(key));
|
||||
const kbErrorMessage = (e: unknown, fallbackKey: string) =>
|
||||
@@ -300,11 +302,17 @@ export const getKbDocumentVersions = async (
|
||||
return getJson<KbDocumentVersionItem[]>(`/api/kb/documents/${documentId}/versions`, []);
|
||||
};
|
||||
|
||||
/**
|
||||
* 拉取知识库版本原始文件,供作业面触发本地下载。
|
||||
* 核心逻辑:带 download=1 走附件响应;文件名优先 RFC 5987 filename*,失败由调用方回退 source_file_name。
|
||||
* @param versionId - 文档版本 ID
|
||||
* @returns 成功时含 blob 与解析出的文件名;失败时 ok=false
|
||||
*/
|
||||
export const getKbDocumentVersionSourceFile = async (
|
||||
versionId: number
|
||||
): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, {
|
||||
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file?download=1`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
@@ -318,13 +326,10 @@ export const getKbDocumentVersionSourceFile = async (
|
||||
}
|
||||
return { ok: false, error: message };
|
||||
}
|
||||
const disposition = res.headers.get('content-disposition') || '';
|
||||
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
|
||||
const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || '');
|
||||
return {
|
||||
ok: true,
|
||||
blob: await res.blob(),
|
||||
filename: filename || undefined,
|
||||
filename: parseContentDispositionFilename(res.headers.get('content-disposition')),
|
||||
contentType: res.headers.get('content-type') || undefined,
|
||||
};
|
||||
} catch {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
/**
|
||||
* features/kb/composables/kb-workspace/useKbWorkspaceModals.ts
|
||||
* 记录/来源/Markdown/失败弹窗与原始文件预览。
|
||||
* 用途:记录/来源/Markdown/失败弹窗与原始文件下载。
|
||||
* 依赖:kb.api、kb-workspace state/computed/data、shared/utils/download。
|
||||
* 逻辑:KbWorkspaceOverlays 调用;源文件点击只触发一次 a[download],保存名与上传时一致。
|
||||
*/
|
||||
import { triggerBlobDownload } from '@/shared/utils/download';
|
||||
import type { KbDocumentItem, KbDocumentMarkdown, KbDocumentVersionItem } from '../../api/kb.api';
|
||||
import {
|
||||
getKbDocumentMarkdown,
|
||||
@@ -74,6 +77,11 @@ export function useKbWorkspaceModals(
|
||||
showSourceInfoModal.value = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 下载当前版本的原始文件,保存名与上传时的源文件名一致。
|
||||
* 核心逻辑:拉 blob 后只触发一次 a[download];不用 window.open blob URL,避免再下一份 UUID 名文件。
|
||||
* @param version - 源文件信息弹窗中的版本项
|
||||
*/
|
||||
const openOriginalSourceFile = async (version: KbDocumentVersionItem) => {
|
||||
openingSourceVersionId.value = version.id;
|
||||
const result = await getKbDocumentVersionSourceFile(version.id);
|
||||
@@ -84,15 +92,8 @@ export function useKbWorkspaceModals(
|
||||
return;
|
||||
}
|
||||
|
||||
const objectUrl = window.URL.createObjectURL(result.blob);
|
||||
const opened = window.open(objectUrl, '_blank', 'noopener,noreferrer');
|
||||
if (!opened) {
|
||||
const link = window.document.createElement('a');
|
||||
link.href = objectUrl;
|
||||
link.download = result.filename || version.source_file_name || `source-${version.id}`;
|
||||
link.click();
|
||||
}
|
||||
window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 60_000);
|
||||
const filename = version.source_file_name || result.filename || `source-${version.id}`;
|
||||
triggerBlobDownload(result.blob, filename);
|
||||
};
|
||||
|
||||
const openFailureModal = (type: 'upload' | 'clean' | 'sync') => {
|
||||
|
||||
@@ -284,7 +284,7 @@
|
||||
"loading": "Loading source file info...",
|
||||
"empty": "No source file info. Upload a version to see it here.",
|
||||
"currentVersion": "Current version",
|
||||
"opening": "Opening...",
|
||||
"opening": "Downloading...",
|
||||
"fileName": "File: {name}",
|
||||
"fileSize": "Size: {size}",
|
||||
"fileType": "Type: {ext}"
|
||||
|
||||
@@ -284,7 +284,7 @@
|
||||
"loading": "กำลังโหลดข้อมูลไฟล์ต้นฉบับ...",
|
||||
"empty": "ยังไม่มีข้อมูลไฟล์ต้นฉบับ อัปโหลดเวอร์ชันเพื่อดูที่นี่",
|
||||
"currentVersion": "เวอร์ชันปัจจุบัน",
|
||||
"opening": "กำลังเปิด...",
|
||||
"opening": "กำลังดาวน์โหลด...",
|
||||
"fileName": "ไฟล์: {name}",
|
||||
"fileSize": "ขนาด: {size}",
|
||||
"fileType": "ประเภท: {ext}"
|
||||
|
||||
@@ -284,7 +284,7 @@
|
||||
"loading": "正在加载源文件信息...",
|
||||
"empty": "暂无源文件信息,上传版本后会显示在这里。",
|
||||
"currentVersion": "当前版本",
|
||||
"opening": "正在打开...",
|
||||
"opening": "正在下载...",
|
||||
"fileName": "文件名:{name}",
|
||||
"fileSize": "大小:{size}",
|
||||
"fileType": "类型:{ext}"
|
||||
|
||||
@@ -284,7 +284,7 @@
|
||||
"loading": "正在載入源文件信息...",
|
||||
"empty": "暫無源文件信息,上傳版本後會顯示在這裡。",
|
||||
"currentVersion": "當前版本",
|
||||
"opening": "正在打開...",
|
||||
"opening": "正在下載...",
|
||||
"fileName": "文件名:{name}",
|
||||
"fileSize": "大小:{size}",
|
||||
"fileType": "類型:{ext}"
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/**
|
||||
* shared/api/client.ts
|
||||
* 跨域 HTTP 客户端:envelope 解析、BusinessError、requestJson、requestBlob。
|
||||
* 依赖:auth、vue-i18n、shared/utils/download(Content-Disposition 文件名)。
|
||||
* 所有 feature API 层应通过此模块发起请求;二进制下载走 requestBlob,失败仍为 BusinessError。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { parseContentDispositionFilename } from '@/shared/utils/download';
|
||||
import i18n from '@/i18n';
|
||||
|
||||
export interface ApiSuccessEnvelope<T> {
|
||||
@@ -217,11 +219,9 @@ export async function requestBlob(url: string, init?: RequestInit): Promise<Blob
|
||||
}
|
||||
|
||||
const blob = await res.blob();
|
||||
const disposition = res.headers.get('Content-Disposition') || '';
|
||||
const filename = disposition.match(/filename\*?=(?:UTF-8''|")?([^";]+)"?/i)?.[1];
|
||||
return {
|
||||
blob,
|
||||
filename: filename ? decodeURIComponent(filename) : undefined,
|
||||
filename: parseContentDispositionFilename(res.headers.get('Content-Disposition')),
|
||||
requestId: requestIdHeader,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* shared/utils/download.test.ts
|
||||
* 用途:校验 Content-Disposition 解析与单次 blob 下载不会拼出怪名。
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
parseContentDispositionFilename,
|
||||
sanitizeDownloadFilename,
|
||||
triggerBlobDownload,
|
||||
} from './download';
|
||||
|
||||
describe('parseContentDispositionFilename', () => {
|
||||
it('prefers RFC 5987 filename* over ASCII fallback', () => {
|
||||
// 断言:Werkzeug/Flask 中文名会留下 ASCII 回退段,必须取 filename*。
|
||||
const encoded = encodeURIComponent('企业文化.docx');
|
||||
const disposition = `attachment; filename="download.docx"; filename*=UTF-8''${encoded}`;
|
||||
expect(parseContentDispositionFilename(disposition)).toBe('企业文化.docx');
|
||||
});
|
||||
|
||||
it('does not concatenate unquoted ASCII fallback with filename*', () => {
|
||||
// 断言:旧实现会得到 `docx; filename_=UTF-8''企业文化.docx`。
|
||||
const encoded = encodeURIComponent('企业文化.docx');
|
||||
const disposition = `inline; filename=docx; filename*=UTF-8''${encoded}`;
|
||||
expect(parseContentDispositionFilename(disposition)).toBe('企业文化.docx');
|
||||
});
|
||||
|
||||
it('reads quoted filename when filename* is absent', () => {
|
||||
expect(parseContentDispositionFilename('attachment; filename="report.pdf"')).toBe('report.pdf');
|
||||
});
|
||||
|
||||
it('returns undefined for empty header', () => {
|
||||
expect(parseContentDispositionFilename('')).toBeUndefined();
|
||||
expect(parseContentDispositionFilename(null)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeDownloadFilename', () => {
|
||||
it('keeps only the last path segment', () => {
|
||||
expect(sanitizeDownloadFilename('dir/企业文化.docx')).toBe('企业文化.docx');
|
||||
});
|
||||
});
|
||||
|
||||
describe('triggerBlobDownload', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('clicks a single anchor with the original filename', () => {
|
||||
// 断言:一次下载只产生一个 a[download],文件名与源文件一致。
|
||||
const clicks: string[] = [];
|
||||
const createObjectURL = vi.fn(() => 'blob:http://localhost/fake');
|
||||
const revokeObjectURL = vi.fn();
|
||||
vi.stubGlobal('URL', { createObjectURL, revokeObjectURL });
|
||||
|
||||
const originalCreateElement = document.createElement.bind(document);
|
||||
vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {
|
||||
const el = originalCreateElement(tagName);
|
||||
if (tagName === 'a') {
|
||||
vi.spyOn(el, 'click').mockImplementation(() => {
|
||||
clicks.push(el.download);
|
||||
});
|
||||
}
|
||||
return el;
|
||||
});
|
||||
|
||||
triggerBlobDownload(new Blob(['hello']), '企业文化.docx');
|
||||
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(1);
|
||||
expect(clicks).toEqual(['企业文化.docx']);
|
||||
expect(document.body.querySelectorAll('a')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* shared/utils/download.ts
|
||||
* 用途:浏览器受控下载的文件名解析与单次触发,避免 blob URL 被 window.open 再下一份。
|
||||
* 依赖:无业务模块;仅使用 DOM URL / a[download]。
|
||||
* 逻辑:requestBlob、知识库源文件等调用;Content-Disposition 优先 RFC 5987 filename*。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 去掉路径与非法换行,得到可写入 a[download] 的纯文件名。
|
||||
* 核心逻辑:只保留最后一段路径分量,避免把目录或响应头片段写进保存名。
|
||||
* @param filename - 原始或解析得到的文件名
|
||||
* @param fallback - 清洗后为空时的回退名
|
||||
* @returns 可安全用作下载名的字符串
|
||||
*/
|
||||
export function sanitizeDownloadFilename(filename: string, fallback = 'download'): string {
|
||||
const name = String(filename || '').replace(/\\/g, '/').split('/').pop()?.trim() || '';
|
||||
const cleaned = name.replace(/[\r\n"]/g, '');
|
||||
return cleaned || fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Content-Disposition 解析下载文件名,优先 RFC 5987 的 filename*。
|
||||
* 核心逻辑:先取 filename*=UTF-8'',再取带引号或到分号为止的 filename=。
|
||||
* 不能用贪婪的 filename="?([^"]+)"?,否则会把 `filename=docx; filename*=UTF-8''原名.docx` 整段当成文件名。
|
||||
* @param disposition - 响应头原文
|
||||
* @returns 解码后的文件名;无法解析时返回 undefined
|
||||
*/
|
||||
export function parseContentDispositionFilename(
|
||||
disposition: string | null | undefined,
|
||||
): string | undefined {
|
||||
const value = String(disposition || '');
|
||||
if (!value) return undefined;
|
||||
|
||||
const utf8Match = value.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);
|
||||
const quotedMatch = value.match(/filename\s*=\s*"([^"]+)"/i);
|
||||
const unquotedMatch = value.match(/filename\s*=\s*([^;]+)/i);
|
||||
const raw = (utf8Match?.[1] || quotedMatch?.[1] || unquotedMatch?.[1] || '').trim();
|
||||
if (!raw) return undefined;
|
||||
|
||||
let decoded = raw;
|
||||
try {
|
||||
decoded = decodeURIComponent(raw);
|
||||
} catch {
|
||||
decoded = raw;
|
||||
}
|
||||
const name = sanitizeDownloadFilename(decoded, '');
|
||||
return name || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 blob 触发一次浏览器下载,保存名使用给定文件名。
|
||||
* 核心逻辑:只创建一条 a[download] 并 click;禁止 window.open blob URL,
|
||||
* 因为 docx 等无法预览的类型会再下一份 UUID 名文件,且 noopener 使 open 返回 null 导致双下载。
|
||||
* @param blob - 文件内容
|
||||
* @param filename - 保存文件名,应与源文件名一致
|
||||
*/
|
||||
export function triggerBlobDownload(blob: Blob, filename: string): void {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = objectUrl;
|
||||
link.download = sanitizeDownloadFilename(filename);
|
||||
link.rel = 'noopener';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
|
||||
}
|
||||
Reference in new issue
Block a user