68 lines
2.8 KiB
TypeScript
68 lines
2.8 KiB
TypeScript
/**
|
||
* 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);
|
||
}
|