36 lines
1.3 KiB
Python
36 lines
1.3 KiB
Python
import shutil
|
||
from pathlib import Path
|
||
from fastapi import APIRouter, UploadFile, File, Depends, HTTPException
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
from app.db.database import get_db
|
||
from app.db.models import File as FileModel
|
||
from app.db.crud import save_file_metadata
|
||
|
||
router = APIRouter()
|
||
STORAGE_PATH = Path("storage")
|
||
STORAGE_PATH.mkdir(exist_ok=True) # Создаем папку, если её нет
|
||
|
||
|
||
@router.post("/upload/")
|
||
async def upload_file(file: UploadFile = File(...), db: AsyncSession = Depends(get_db)):
|
||
file_path = STORAGE_PATH / file.filename
|
||
|
||
# Проверяем, существует ли файл
|
||
if file_path.exists():
|
||
raise HTTPException(status_code=400, detail="Файл с таким именем уже существует")
|
||
|
||
# Сохраняем файл на диск
|
||
with file_path.open("wb") as buffer:
|
||
shutil.copyfileobj(file.file, buffer)
|
||
|
||
# Сохраняем метаданные файла в БД
|
||
file_metadata = await save_file_metadata(
|
||
db=db,
|
||
filename=file.filename,
|
||
filepath=str(file_path),
|
||
content_type=file.content_type,
|
||
size=file_path.stat().st_size
|
||
)
|
||
|
||
return {"message": "Файл успешно загружен", "file_id": file_metadata.id}
|