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

This commit is contained in:
HTEWJ\26070045 committed 2026-09-09 15:43:14 +08:00
1 parent dabf140e41
commit a768eb9024
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()