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

如何在FastAPI中实现支持多扩展名的文件下载功能?

解决FastAPI通用文件下载的MIME类型问题
  • 你当前用application/tar+gzip只适用于压缩包,完全不通用。正确的做法是根据文件扩展名自动匹配对应MIME类型,或者用通用二进制流类型兜底。
  • 直接用Python标准库mimetypes就能实现自动识别,修改后的代码如下:
import mimetypes
from fastapi import FastAPI, Response

app = FastAPI()

@app.get("/myurl")
def get_file(myfilename: str):
    mydata = fetch_file_from_server(myfilename)
    # 获取文件对应的MIME类型,找不到则用通用二进制流
    content_type, _ = mimetypes.guess_type(myfilename)
    media_type = content_type or "application/octet-stream"
    
    headers = {"content-disposition": f"attachment; filename=\"{myfilename}\""}
    return Response(content=mydata, media_type=media_type, headers=headers)
  • 关键说明:
    • mimetypes.guess_type()会根据文件名后缀返回对应的MIME类型(比如.json返回application/json,.txt返回text/plain)
    • 如果遇到不识别的扩展名,就用application/octet-stream——这是通用的二进制文件类型,浏览器会直接触发下载,不会尝试打开
    • 保持content-disposition的attachment参数,确保浏览器以下载方式处理文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 18:52:01