You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI StreamingResponse下载文件名异常如何自定义设置

问题根因

返回StreamingResponse时未显式配置Content-Disposition响应头,Swagger UI/浏览器无法从响应中解析到合法的下载文件名,会自动拼接请求路径、参数、服务端标识等内容生成默认文件名,最终出现混杂IP、UUID、接口参数片段的异常命名。

修复方法
  • 构造StreamingResponse对象时,手动传入headers参数,在响应头中明确声明下载文件名,即可完全自定义文件名,适配zip、gz等任意返回格式。
  • 基础用法代码示例:
from fastapi.responses import StreamingResponse
import io
import gzip
import zipfile

# gz格式返回示例
def gz_stream_endpoint():
    # 替换为实际的流生成逻辑
    buffer = io.BytesIO()
    with gzip.GzipFile(fileobj=buffer, mode="wb") as gz_file:
        gz_file.write(b"your export content")
    buffer.seek(0)

    # 核心:指定响应头声明文件名
    resp_headers = {
        "Content-Disposition": 'attachment; filename="your_custom_name.gz"'
    }
    return StreamingResponse(
        buffer,
        media_type="application/gzip",
        headers=resp_headers
    )

# zip格式返回示例
def zip_stream_endpoint():
    # 替换为实际的流生成逻辑
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
        zip_file.writestr("readme.txt", "your export content")
    buffer.seek(0)

    resp_headers = {
        "Content-Disposition": 'attachment; filename="your_custom_name.zip"'
    }
    return StreamingResponse(
        buffer,
        media_type="application/zip",
        headers=resp_headers
    )
  • 若需要使用中文等非ASCII文件名,补充filename*字段做兼容即可,响应头写法调整为:
    Content-Disposition: attachment; filename="fallback_export.gz"; filename*=UTF-8''URL编码后的中文文件名
    
    其中filename字段作为老旧浏览器的回退名称,filename*字段遵循RFC 5987规范,适配所有现代浏览器的非ASCII文件名解析。

配置完成后,无论是通过Swagger UI触发下载,还是直接调用接口,都会使用你指定的文件名,不会再生成混杂无关内容的异常名称。


内容的提问来源于stack exchange,提问作者Omri. B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 23:42:19