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