fix: 修改一下生图的 bug

This commit is contained in:
2026-08-31 21:56:48 +08:00
parent 2a667b4f3b
commit 8b54f7ed1e
14 changed files with 636 additions and 47 deletions
+12 -1
View File
@@ -13,6 +13,7 @@ import re
import tempfile
import zipfile
from collections.abc import Iterator
from urllib.parse import quote
from fastapi import APIRouter, HTTPException
from fastapi.responses import Response, StreamingResponse
@@ -80,6 +81,16 @@ def _is_image(url: str, ctype: str) -> bool:
return bool(re.search(r"\.(jpe?g|png|webp|gif|bmp)(\?|$)", url, re.IGNORECASE))
def _download_disposition(filename: str) -> str:
"""生成兼容中文文件名的下载响应头。
Starlette 会按 Latin-1 编码 HTTP 头;直接将中文放进 filename 会抛 UnicodeEncodeError
并返回 500。filename 提供 ASCII 回退,filename* 使用 RFC 5987 的 UTF-8 百分号编码。
"""
fallback = re.sub(r"[^\x20-\x7e]", "_", filename) or "image"
return f"attachment; filename=\"{fallback}\"; filename*=UTF-8''{quote(filename, safe='')}"
async def _download(url: str) -> tuple[bytes, str]:
"""本地 media 文件直读磁盘;远程 URL(源站 CDN / 七牛)带 Referer 下载。"""
path = local_path(url)
@@ -190,5 +201,5 @@ async def export_image(img: ExportImageItem):
return Response(
content=data,
media_type=ctype,
headers={"Content-Disposition": f'attachment; filename="{base}{ext}"'},
headers={"Content-Disposition": _download_disposition(f"{base}{ext}")},
)