1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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": "沒有此文件"
}