Files
problem-bank/backend/services/file_utils.py
2026-03-06 15:52:34 +08:00

32 lines
963 B
Python

import shutil
from pathlib import Path
from fastapi import UploadFile
from backend.config import settings
def ensure_upload_dir() -> Path:
target = Path(settings.upload_dir)
target.mkdir(parents=True, exist_ok=True)
return target
def save_upload(upload_file: UploadFile) -> Path:
target_dir = ensure_upload_dir()
target_path = target_dir / upload_file.filename
with target_path.open("wb") as buffer:
shutil.copyfileobj(upload_file.file, buffer)
return target_path
def save_upload_for_job(job_id: int, seq: int, upload_file: UploadFile) -> Path:
"""Save file with unique path under upload_dir/job_id/ to avoid overwrites."""
base = ensure_upload_dir() / str(job_id)
base.mkdir(parents=True, exist_ok=True)
name = upload_file.filename or "file"
target_path = base / f"{seq}_{name}"
with target_path.open("wb") as buffer:
shutil.copyfileobj(upload_file.file, buffer)
return target_path