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": "沒有此文件"
}