50 lines
1.1 KiB
Python
50 lines
1.1 KiB
Python
from pathlib import Path
|
|
from loguru import logger
|
|
from fastapi import FastAPI, HTTPException, Request
|
|
from fastapi.responses import FileResponse
|
|
import aiofiles
|
|
|
|
|
|
def mk_upload_dir():
|
|
import os
|
|
os.makedirs("upload", exist_ok=True)
|
|
|
|
|
|
mk_upload_dir()
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
@app.get("/{file:path}")
|
|
def download(file: str) -> FileResponse:
|
|
file = "/"+file
|
|
|
|
logger.info(f"Downloading {file}")
|
|
file_path = Path("upload") / file
|
|
if not file_path.exists():
|
|
raise HTTPException(status_code=404, detail="File not found")
|
|
return FileResponse(path=file, filename=file)
|
|
|
|
|
|
@app.post("/{file:path}")
|
|
async def upload(file: str, request: Request) -> dict:
|
|
logger.info(f"Uploading {file}")
|
|
|
|
# 确保目录存在
|
|
full_path = Path("upload") / file
|
|
full_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
# 流式写入文件
|
|
total_size = 0
|
|
async with aiofiles.open(full_path, 'wb') as f:
|
|
async for chunk in request.stream():
|
|
await f.write(chunk)
|
|
total_size += len(chunk)
|
|
|
|
return {
|
|
"status": "success",
|
|
"file": file,
|
|
"size": total_size,
|
|
"path": full_path
|
|
}
|