fix(attachments): 文本附件打开中文乱码——aiohttp FileResponse按扩展名猜Content-Type不附charset,text/plain无charset浏览器按ISO-8859-1解UTF-8;服务端显式设charset=utf-8,未知扩展名纯文本归text/plain内联

This commit is contained in:
yumoqing 2026-09-11 13:21:32 +08:00
parent 18f74101f9
commit eb5393f299

View File

@ -30,4 +30,21 @@ else:
headers['Content-Disposition'] = (
'inline; filename="%s"; filename*=UTF-8\'\'%s' % (fname, safe_name))
# 文本类显式带 charset=utf-8aiohttp FileResponse 按扩展名猜 Content-Type 不附
# charsettext/plain 无 charset 时浏览器按 ISO-8859-1 解 UTF-8 → 中文乱码
# 2026-09-11 用户报障。未知扩展名的纯文本log/conf 等)也归入 text/plain 内联展示。
import mimetypes as _mt
_ctype = _mt.guess_type(fname)[0] or ''
if not _ctype:
_ext = fname.rsplit('.', 1)[-1].lower() if '.' in fname else ''
if _ext in ('txt', 'log', 'md', 'csv', 'conf', 'ini', 'yml', 'yaml',
'py', 'js', 'sh', 'sql', 'json'):
_ctype = 'text/plain'
if _ctype.startswith('text/') or _ctype in (
'application/json', 'application/javascript',
'application/xml', 'image/svg+xml'):
_ctype += '; charset=utf-8'
if _ctype:
headers['Content-Type'] = _ctype
return FileResponse(full_path, headers=headers)