!18 fix(knowledgeBase): 知识库下载文件命名不对

Merge pull request !18 from sophie/fix-bug
This commit is contained in:
sophie authored and Gitee committed 2026-09-09 07:50:07 +00:00
commit 60d4f06018
13 files changed
+299 -28

No files matched your search

+29 -1
View File
@@ -1,10 +1,13 @@
"""
backend/app/api/kb/common.py
用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览)。
用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览、下载头)。
依赖:app.core.*、models、services/kb/storage、edkb_system。
逻辑:dify/groups/documents/jobs 子模块共用;存储读写见 services/kb/storage。
"""
from pathlib import Path
from urllib.parse import quote
from flask import current_app
from sqlalchemy.exc import DatabaseError, OperationalError
@@ -31,6 +34,31 @@ def require_user():
raise UnauthorizedError()
return user
def build_content_disposition(filename: str, *, as_attachment: bool = True) -> str:
"""
构造 RFC 5987 Content-Disposition,保证中文源文件名不被浏览器拼成怪名。
核心逻辑:quoted ASCII 回退名(保留扩展名)+ filename*=UTF-8''百分号编码原名。
浏览器优先 filename*;旧客户端才用 ASCII 回退。ASCII 段必须加引号且不含分号。
Args:
filename: 用户可见的原始文件名。禁止路径分隔与换行。
as_attachment: True 为下载(attachment),False 为预览(inline)。
Returns:
可直接写入响应头的 Content-Disposition 字符串。
"""
safe_name = Path(str(filename or '').replace('\\', '/')).name
safe_name = safe_name.replace('\r', '').replace('\n', '').replace('"', '').strip() or 'download'
suffix = Path(safe_name).suffix
stem_ascii = Path(safe_name).stem.encode('ascii', 'ignore').decode('ascii').strip() or 'download'
ascii_name = f'{stem_ascii}{suffix}' if suffix else stem_ascii
encoded = quote(safe_name, safe='')
disposition = 'attachment' if as_attachment else 'inline'
return f'{disposition}; filename="{ascii_name}"; filename*=UTF-8\'\'{encoded}'
def run_db_read(label: str, loader):
try:
return loader()
+20 -4
View File
@@ -3,13 +3,19 @@ backend/app/api/kb/documents.py
用途:知识库文档版本、Markdown、上传/清洗/同步 API(薄路由层)。
依赖:kb.blueprint、kb.common、services/kb/document_service。
逻辑:/documents* 与 /document-versions* 路由;业务见 document_service。
逻辑:/documents* 与 /document-versions* 路由;业务见 document_service;源文件下载覆盖 RFC 5987 Content-Disposition。
"""
from flask import jsonify, request, send_file
from app import db
from app.api.kb.blueprint import knowledge_base_bp
from app.api.kb.common import require_user, serialize_document, serialize_sync_record, serialize_version
from app.api.kb.common import (
build_content_disposition,
require_user,
serialize_document,
serialize_sync_record,
serialize_version,
)
from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.services.kb import document_service
@@ -24,10 +30,18 @@ def list_document_versions(document_id: int):
@knowledge_base_bp.route('/document-versions/<int:version_id>/source-file', methods=['GET'])
def get_document_version_source_file(version_id: int):
"""
返回知识库版本原始文件。
用途:工作台源文件信息弹窗下载原件;?download=1 时按附件下发,保存名与上传时一致。
核心逻辑:send_file 后再覆盖 Content-Disposition 为 RFC 5987,避免 Werkzeug ASCII 回退名无引号导致浏览器拼名。
"""
require_user()
source_path, filename = document_service.resolve_source_file_path(version_id)
as_attachment = str(request.args.get('download') or '').strip() == '1'
return send_file(source_path, as_attachment=as_attachment, download_name=filename)
response = send_file(source_path, as_attachment=as_attachment, download_name=filename)
response.headers['Content-Disposition'] = build_content_disposition(filename, as_attachment=as_attachment)
return response
@knowledge_base_bp.route('/document-versions/<int:version_id>/training-preview-file', methods=['GET'])
@@ -41,7 +55,9 @@ def get_training_preview_file(version_id: int):
require_user()
preview_path, filename = document_service.resolve_training_preview_file_path(version_id)
as_attachment = str(request.args.get('download') or '').strip() == '1'
return send_file(preview_path, as_attachment=as_attachment, download_name=filename)
response = send_file(preview_path, as_attachment=as_attachment, download_name=filename)
response.headers['Content-Disposition'] = build_content_disposition(filename, as_attachment=as_attachment)
return response
@knowledge_base_bp.route('/documents/<int:document_id>/sync-records', methods=['GET'])
@@ -0,0 +1,80 @@
"""
tests/test_kb_source_file_download.py
用途:知识库源文件下载的 Content-Disposition 与中文文件名。
依赖:kb.common.build_content_disposition、documents 路由、kb 模型。
逻辑:纯函数校验 RFC 5987 头;API 用例确认 ?download=1 返回原名且正文为原件。
"""
from pathlib import Path
from urllib.parse import quote
from app import db
from app.api.kb.common import build_content_disposition
from app.core.auth.jwt import issue_local_access_token
from app.models import KbDocument, KbDocumentVersion, KbGroup, User
def test_build_content_disposition_quotes_ascii_and_keeps_utf8_filename():
"""
ASCII 回退名必须加引号,真实中文名在 filename* 段。
关键断言:不得出现无引号的 `filename=docx; filename*=...`,否则浏览器会把两段拼成怪名。
"""
filename = '企业文化.docx'
header = build_content_disposition(filename, as_attachment=True)
assert header.startswith('attachment; filename="download.docx"; filename*=UTF-8\'\'')
assert quote(filename, safe='') in header
assert 'filename=docx;' not in header
def test_source_file_download_uses_original_filename(app, client, tmp_path):
"""
工作台源文件下载应以下载附件返回,且 Content-Disposition 含原始中文文件名。
关键断言:响应体是原件字节;filename* 为 企业文化.docx;ASCII 回退名带引号。
"""
storage_root = tmp_path / 'kb-storage'
storage_root.mkdir()
source_name = '企业文化.docx'
source_path = storage_root / 'corp-culture.docx'
source_bytes = b'PK\x03\x04fake-docx'
source_path.write_bytes(source_bytes)
app.config['KB_STORAGE_ROOT'] = str(storage_root)
with app.app_context():
user = User(
username='kb-download-admin',
email='kb-download-admin@example.com',
role='admin',
status='active',
)
user.set_password('password123')
group = KbGroup(name='源文件下载分组')
document = KbDocument(group=group, title='企业文化', status='uploaded')
version = KbDocumentVersion(
document=document,
version_no=1,
status='uploaded',
is_current=True,
source_file_name=source_name,
source_file_path=str(source_path),
source_file_ext='docx',
source_file_size=len(source_bytes),
)
db.session.add_all([user, group, document, version])
db.session.commit()
version_id = version.id
token = issue_local_access_token(user)
res = client.get(
f'/api/kb/document-versions/{version_id}/source-file?download=1',
headers={'Authorization': f'Bearer {token}'},
)
assert res.status_code == 200
assert res.data == source_bytes
disposition = res.headers.get('Content-Disposition', '')
assert 'attachment' in disposition
assert f'filename*=UTF-8\'\'{quote(source_name, safe="")}' in disposition
assert 'filename="download.docx"' in disposition
assert 'filename=docx;' not in disposition
+1
View File
@@ -28,6 +28,7 @@
- Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。
- 管理端“知识库配置 → Dify 设置”支持配置新建 Dataset 的默认检索模型(检索方式、重排序、Top K、相似度阈值开关及阈值),以及文档同步的自定义分段参数(最大 Token 数、重叠 Token 数);保存仅更新 HXOPS 运行时配置,不自动回写已创建的 Dify Dataset。
- Excel/CSV 分段使用独立配置 `KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL`(默认 1200)和表格行组段上限 `table_segment_max_chars`(默认 1000);普通文档仍使用 `KB_DIFY_SEGMENT_MAX_TOKENS`(默认 600)。
- 工作台知识库源文件下载保存名为上传时的原始文件名;一次点击只触发一次下载。
## 设备维保助手
+11 -6
View File
@@ -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') => {
+1 -1
View File
@@ -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}"
+1 -1
View File
@@ -284,7 +284,7 @@
"loading": "กำลังโหลดข้อมูลไฟล์ต้นฉบับ...",
"empty": "ยังไม่มีข้อมูลไฟล์ต้นฉบับ อัปโหลดเวอร์ชันเพื่อดูที่นี่",
"currentVersion": "เวอร์ชันปัจจุบัน",
"opening": "กำลังเปิด...",
"opening": "กำลังดาวน์โหลด...",
"fileName": "ไฟล์: {name}",
"fileSize": "ขนาด: {size}",
"fileType": "ประเภท: {ext}"
+1 -1
View File
@@ -284,7 +284,7 @@
"loading": "正在加载源文件信息...",
"empty": "暂无源文件信息,上传版本后会显示在这里。",
"currentVersion": "当前版本",
"opening": "正在打开...",
"opening": "正在下载...",
"fileName": "文件名:{name}",
"fileSize": "大小:{size}",
"fileType": "类型:{ext}"
+1 -1
View File
@@ -284,7 +284,7 @@
"loading": "正在載入源文件信息...",
"empty": "暫無源文件信息,上傳版本後會顯示在這裡。",
"currentVersion": "當前版本",
"opening": "正在打開...",
"opening": "正在下載...",
"fileName": "文件名:{name}",
"fileSize": "大小:{size}",
"fileType": "類型:{ext}"
+3 -3
View File
@@ -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);
});
});
+67
View File
@@ -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);
}