2026-02-11 22:40:35 +08:00
|
|
|
# utils/file_handler.py
|
|
|
|
|
import aiofiles
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
from fastapi import UploadFile
|
2026-03-15 13:33:47 +08:00
|
|
|
from typing import Tuple
|
2026-02-11 22:40:35 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class FileHandler:
|
|
|
|
|
def __init__(self, upload_dir: str = "uploads"):
|
|
|
|
|
self.upload_dir = Path(upload_dir)
|
|
|
|
|
self.upload_dir.mkdir(exist_ok=True)
|
|
|
|
|
|
2026-03-15 13:33:47 +08:00
|
|
|
async def save_uploaded_file(self, file: UploadFile) -> Tuple[Path, int]:
|
2026-02-11 22:40:35 +08:00
|
|
|
"""保存上传的文件"""
|
|
|
|
|
file_path = self.upload_dir / file.filename
|
|
|
|
|
|
2026-03-15 13:33:47 +08:00
|
|
|
content = await file.read()
|
2026-02-11 22:40:35 +08:00
|
|
|
async with aiofiles.open(file_path, 'wb') as f:
|
|
|
|
|
await f.write(content)
|
|
|
|
|
|
2026-03-15 13:33:47 +08:00
|
|
|
return file_path, len(content)
|
2026-02-11 22:40:35 +08:00
|
|
|
|
|
|
|
|
def cleanup_file(self, file_path: Path):
|
|
|
|
|
"""清理文件"""
|
|
|
|
|
try:
|
|
|
|
|
if file_path.exists():
|
|
|
|
|
file_path.unlink()
|
|
|
|
|
except Exception as e:
|
2026-03-15 13:33:47 +08:00
|
|
|
print(f"文件清理失败: {e}")
|