24 lines
557 B
Python
24 lines
557 B
Python
from __future__ import annotations
|
|
|
|
import os
|
|
import uuid
|
|
|
|
from fastapi import UploadFile
|
|
|
|
UPLOAD_DIR = "uploads"
|
|
|
|
|
|
async def save_upload(file: UploadFile, subdir: str = "") -> str:
|
|
directory = os.path.join(UPLOAD_DIR, subdir) if subdir else UPLOAD_DIR
|
|
os.makedirs(directory, exist_ok=True)
|
|
|
|
ext = os.path.splitext(file.filename or "")[1]
|
|
filename = f"{uuid.uuid4().hex}{ext}"
|
|
filepath = os.path.join(directory, filename)
|
|
|
|
content = await file.read()
|
|
with open(filepath, "wb") as f:
|
|
f.write(content)
|
|
|
|
return filepath
|