Files
stemengine_old/backend/services/upload_io.py
T
2026-04-14 16:32:36 +09:00

21 lines
700 B
Python

from pathlib import Path
from fastapi import UploadFile
async def save_upload_file(upload: UploadFile, destination: Path, *, chunk_size: int = 1024 * 1024) -> None:
"""Persist an uploaded file using async reads and writes.
This avoids blocking sync copy operations inside async route handlers.
"""
destination.parent.mkdir(parents=True, exist_ok=True)
# pathlib.Path.open is sync; keep writes chunked and combine with async reads
# to avoid full-memory buffering in request handlers.
with destination.open("wb") as out:
while True:
chunk = await upload.read(chunk_size)
if not chunk:
break
out.write(chunk)