init
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
# utils/file_handler.py
|
||||
import aiofiles
|
||||
from pathlib import Path
|
||||
from fastapi import UploadFile
|
||||
|
||||
|
||||
class FileHandler:
|
||||
def __init__(self, upload_dir: str = "uploads"):
|
||||
self.upload_dir = Path(upload_dir)
|
||||
self.upload_dir.mkdir(exist_ok=True)
|
||||
|
||||
async def save_uploaded_file(self, file: UploadFile) -> Path:
|
||||
"""保存上传的文件"""
|
||||
file_path = self.upload_dir / file.filename
|
||||
|
||||
async with aiofiles.open(file_path, 'wb') as f:
|
||||
content = await file.read()
|
||||
await f.write(content)
|
||||
|
||||
return file_path
|
||||
|
||||
def cleanup_file(self, file_path: Path):
|
||||
"""清理文件"""
|
||||
try:
|
||||
if file_path.exists():
|
||||
file_path.unlink()
|
||||
except Exception as e:
|
||||
print(f"文件清理失败: {e}")
|
||||
Reference in New Issue
Block a user