Spaces:
Running
Running
File size: 3,447 Bytes
3bafddd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | """
File Upload API - Upload files to Supabase Storage
"""
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException
from uuid import UUID
import time
import logging
from app.core.supabase import supabase_client
from app.api.deps import get_current_user
from app.models.user import User
logger = logging.getLogger(__name__)
router = APIRouter()
@router.post("/file")
async def upload_file(
file: UploadFile = File(...),
current_user: User = Depends(get_current_user)
):
"""
Upload a file to Supabase Storage.
Returns public URL of uploaded file.
"""
if not supabase_client:
raise HTTPException(status_code=500, detail="Storage not configured")
# Validate file
if not file.filename:
raise HTTPException(status_code=400, detail="No filename")
# Read file content
content = await file.read()
if len(content) > 10 * 1024 * 1024: # 10MB limit
raise HTTPException(status_code=400, detail="File too large (max 10MB)")
# Determine bucket based on content type
content_type = file.content_type or "application/octet-stream"
if content_type.startswith("image/"):
bucket = "media"
folder = "images"
elif content_type == "application/pdf":
bucket = "media"
folder = "documents"
elif content_type.startswith("video/"):
bucket = "media"
folder = "videos"
else:
bucket = "media"
folder = "files"
# Generate unique filename
timestamp = int(time.time())
safe_filename = file.filename.replace(" ", "_")
path = f"{current_user.tenant_id}/{folder}/{timestamp}_{safe_filename}"
try:
# Upload to Supabase Storage
result = supabase_client.storage.from_(bucket).upload(
path=path,
file=content,
file_options={"content-type": content_type}
)
# Get public URL
public_url = supabase_client.storage.from_(bucket).get_public_url(path)
logger.info(f"✅ File uploaded: {path} -> {public_url[:60]}...")
return {
"ok": True,
"url": public_url,
"filename": file.filename,
"content_type": content_type,
"size": len(content)
}
except Exception as e:
logger.error(f"❌ Upload failed: {e}")
raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")
@router.post("/image")
async def upload_image(
file: UploadFile = File(...),
current_user: User = Depends(get_current_user)
):
"""
Upload an image file. Validates that it's actually an image.
"""
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File must be an image")
return await upload_file(file, current_user)
@router.post("/document")
async def upload_document(
file: UploadFile = File(...),
current_user: User = Depends(get_current_user)
):
"""
Upload a document (PDF, DOC, etc).
"""
allowed_types = [
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
]
if file.content_type not in allowed_types:
raise HTTPException(status_code=400, detail="File must be PDF or DOC")
return await upload_file(file, current_user)
|