You need to enable JavaScript to run this app. 如何使用FastAPI下载文件?Flask下载接口转FastAPI的代码改写问题
优惠活动
大模型
产品
解决方案
定价
更多

如何使用FastAPI下载文件?Flask下载接口转FastAPI的代码改写问题

Flask 下载接口到FastAPI的等价实现

FastAPI没有提供和Flask send_file 完全同名的便捷方法,对应实现文件下载的核心组件是 fastapi.responses.FileResponse,可以实现和原Flask代码完全一致的行为。

最小等价改写

直接把原Flask接口的逻辑映射为FastAPI写法,核心改动如下:

  • 路由路径格式从 /download/<fname> 改为FastAPI兼容的 /download/{fname}
  • 把直接传文件路径的 send_file(fname) 替换为返回值 FileResponse(path=fname)

对应可运行代码:

from fastapi import FastAPI
from fastapi.responses import FileResponse

app = FastAPI()

@app.get("/download/{fname}")
def download(fname: str):
    # 等价于原Flask的 return send_file(fname)
    return FileResponse(path=fname)

必须补充的安全校验

原Flask实现存在路径遍历漏洞风险:如果直接把URL传入的fname 拼接服务器文件路径,攻击者可以传入类似../../etc/passwd 的特殊文件名,绕过目录限制下载服务器上的敏感文件。

正式环境使用时,需要补充路径校验逻辑,把可下载的文件范围锁定在固定的安全目录下,参考实现如下:

import os
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse

app = FastAPI()
# 定义允许提供下载的根目录,所有可下载文件必须存放在该目录下
ALLOW_DOWNLOAD_DIR = os.path.abspath("./public_download")

@app.get("/download/{fname}")
def download(fname: str):
    # 拼接完整文件路径并做绝对路径归一化
    target_path = os.path.abspath(os.path.join(ALLOW_DOWNLOAD_DIR, fname))
    # 校验目标路径是否处于允许的下载目录内
    if not target_path.startswith(ALLOW_DOWNLOAD_DIR + os.sep):
        raise HTTPException(status_code=403, detail="无权限访问该路径")
    # 校验目标路径是真实存在的普通文件,避免返回目录或特殊文件
    if not os.path.isfile(target_path):
        raise HTTPException(status_code=404, detail="请求的文件不存在")
    return FileResponse(path=target_path)

自定义行为说明

FileResponse 默认会根据文件后缀自动匹配对应的Content-Type,和Flask send_file 的默认行为一致:

  • 如果需要指定用户下载时的展示文件名,可以给FileResponse 传入filename 参数
  • 如果需要禁用浏览器对特定文件的在线预览、强制触发下载,可以额外设置响应头Content-Disposition: attachment

内容的提问来源于stack exchange,提问作者Steven Ramirez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 02:57:01