1. StreamingResponse支持文件类型的操作
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
@app.get("/")
def index():
def iterfile(): #
with open("mybook.zip", mode="rb") as f: #
yield from f
return StreamingResponse(iterfile(), media_type="application/zip")
2. 直接下载FileResponse
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get("/")
def index():
return FileResponse("mybook.zip", filename="book.zip") # 第一个参数文件路径,filename指定下载下来的文件名