fastapi文件上传下载

import os
import time
from fastapi import APIRouter, File, UploadFile
from fastapi.responses import FileResponse
router = APIRouter(tags=['Upload'], prefix='/upload')


@router.post("", summary='文件上传')
def create(uploadfile: UploadFile = File(...)):
    filename = f"{str(time.time()).replace('.','')}-{uploadfile.filename}"
    path = os.path.join("upload", filename)
    with open(path, "wb") as f:
        f.write(uploadfile.file.read())
        f.flush()

    return {
        "filename": filename
    }


@router.get("/{filename}", summary="文件下载")
def read(filename: str):
    file_path = os.path.join("upload", filename)
    if os.path.exists(file_path):
        return FileResponse(file_path)
    else:
        return {
            "msg": "沒有此文件"
        }

posted @ 2023-07-26 10:14  bitterteaer  阅读(338)  评论(0编辑  收藏  举报