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

FastAPI如何无需本地保存直接返回文件?

在FastAPI中直接返回内存中的文件(无需本地存储)

完全可以不用把文件保存到本地再返回,FastAPI支持直接返回内存里生成的文件内容,常用两种实现方式:

方式一:用StreamingResponse配合字节流对象

适合处理大文件,避免一次性把全部内容加载到内存,比如动态生成的Excel、图片等:

from fastapi import FastAPI, StreamingResponse
from io import BytesIO
import pandas as pd

app = FastAPI()

@app.get("/download-excel")
def download_excel():
    # 模拟动态生成数据
    data = {"序号": [1, 2, 3], "内容": ["测试1", "测试2", "测试3"]}
    df = pd.DataFrame(data)
    
    # 将Excel写入内存缓冲区
    buffer = BytesIO()
    df.to_excel(buffer, index=False)
    buffer.seek(0)  # 重置缓冲区指针到开头
    
    return StreamingResponse(
        buffer,
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        headers={"Content-Disposition": "attachment; filename=动态生成表格.xlsx"}
    )

方式二:直接用Response返回字节数据

适合小文件,代码更简洁:

from fastapi import FastAPI, Response

app = FastAPI()

@app.get("/download-text")
def download_text():
    # 动态生成文本内容
    file_content = "这是不用存本地的动态文件内容"
    return Response(
        content=file_content.encode("utf-8"),
        media_type="text/plain",
        headers={"Content-Disposition": "attachment; filename=动态文本.txt"}
    )

关键说明

  • media_type要对应文件类型:文本用text/plain,Excel用上面的类型,图片用image/png等
  • Content-Disposition头用来指定文件名和下载方式(attachment表示触发下载)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 02:54:35