ImageProcessor_MainServer/app/stream_utils.py

30 lines
809 B
Python

# -*- coding: utf-8 -*-
"""
업로드 스트림 → 즉시 Base64 인코딩 (RAM 두 벌 방지)
"""
import base64, io, asyncio
CHUNK = 1024 * 1024 # 1 MB
async def upload_to_b64(upload_file, max_bytes: int) -> str:
"""
UploadFile 객체를 읽으면서 바로 base64 로 인코딩하여 문자열 반환.
"""
encoder = base64.b64encode
buf = io.BytesIO() # max_bytes 이하면 RAM, 초과면 디스크로 자동 이동
size = 0
while True:
chunk = await upload_file.read(CHUNK)
if not chunk:
break
size += len(chunk)
if size > max_bytes:
raise ValueError("file too large")
buf.write(chunk)
if size == 0:
raise ValueError("empty upload")
return encoder(buf.getbuffer()).decode("utf-8")