Files
2025-12-13 14:39:50 +03:00

67 lines
2.1 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from app.api.deps import get_current_active_user
from app.models.user import User
from app.services.storage_service import storage_service
router = APIRouter()
@router.post("/upload")
async def upload_image(
file: UploadFile = File(...),
current_user: User = Depends(get_current_active_user)
):
"""Загрузить изображение"""
# Проверка типа файла
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="File must be an image"
)
# Проверка размера (макс 10MB)
file_content = await file.read()
if len(file_content) > 10 * 1024 * 1024:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="File size must be less than 10MB"
)
try:
# Загружаем файл
from io import BytesIO
file_obj = BytesIO(file_content)
url = await storage_service.upload_file(
file_obj=file_obj,
filename=file.filename or "image.jpg",
content_type=file.content_type
)
return {"url": url, "filename": file.filename}
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to upload image: {str(e)}"
)
@router.delete("/{file_key}")
async def delete_image(
file_key: str,
current_user: User = Depends(get_current_active_user)
):
"""Удалить изображение"""
try:
success = await storage_service.delete_file(file_key)
if not success:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="File not found"
)
return {"message": "File deleted successfully"}
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to delete image: {str(e)}"
)