[FastAPI-42]下载文件相关的Response-StreamingResponse文件类型-FileResponse直接下载

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指定下载下来的文件名
posted @ 2023-03-30 14:20  LeoShi2020  阅读(537)  评论(0编辑  收藏  举报