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

FastAPI中使用Response类下载字节内容时如何指定文件名?

FastAPI从MongoDB下载文件指定文件名的解决方案

FastAPI的Response类并没有像FileResponse那样提供直接的filename参数,但你考虑的通过Content-Disposition响应头指定文件名的方式,就是最标准且有效的方案——这其实也是FileResponse内部实现文件名指定的核心逻辑。

修正后的完整代码

注意修复原代码中content = result["file_data"]的位置问题,避免result为None时触发键值查找错误:

from fastapi import FastAPI, Response, HTTPException
from pymongo import MongoClient

app = FastAPI()
DB = "your_db_name"
FILES_COLLECTION = "your_files_collection"

@app.get("/files/{file_name}", responses={200: {"content": {"text/html": {}}}}, response_class=Response)
def download_file(file_name: str):
    with MongoClient() as client:
        files_collection = client[DB][FILES_COLLECTION]
        result = files_collection.find_one({"file_name": file_name})
    
    if result is not None:
        content = result["file_data"]
        # 可直接使用原文件名,或自定义下载显示的文件名
        download_file_name = file_name
        headers = {
            "Content-Disposition": f'attachment; filename="{download_file_name}"'
        }
        return Response(content=content, headers=headers, media_type="text/html")
    else:
        raise HTTPException(status_code=404, detail="File not found")

特殊字符兼容处理

如果文件名包含中文、空格或其他特殊字符,建议对文件名进行URL编码,避免出现识别异常:

from urllib.parse import quote

# ... 其他代码不变
download_file_name = "包含中文的文件名.html"
# 兼容多场景的编码格式
headers = {
    "Content-Disposition": f'attachment; filename="{download_file_name}"; filename*=UTF-8''{quote(download_file_name)}'
}

设置该响应头后,无论是在Swagger界面下载,还是前端发起请求,都会自动使用你指定的文件名,而非默认的response_SOME-NUMBER.txt。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:12:52