fix(knowledgeBase): 知识库下载文件命名不对
This commit is contained in:
1 parent
dabf140e41
commit
a768eb9024
13 files changed
+299
-28
No files matched your search
@@ -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