Files

33 lines
1.1 KiB
Python

from urllib.parse import unquote
from botocore.exceptions import ClientError
from fastapi import APIRouter, HTTPException
from fastapi.responses import StreamingResponse
from app.s3 import BUCKET_NAME, s3_client
router = APIRouter(prefix="/media", tags=["media"])
@router.get("/{file_path:path}")
async def get_media(file_path: str):
decoded_path = unquote(file_path)
clean_key = decoded_path.lstrip("/")
try:
s3_object = s3_client.get_object(Bucket=BUCKET_NAME, Key=clean_key)
return StreamingResponse(
content=s3_object["Body"].iter_chunks(),
media_type=s3_object.get("ContentType", "application/octet-stream"),
headers={"Cache-Control": "public, max-age=86400"},
)
except ClientError as e:
error_code = e.response["Error"]["Code"]
if error_code in ["NoSuchKey", "404"]:
raise HTTPException(
status_code=404,
detail=f"Fichier introuvable sur S3 pour la clé : '{clean_key}'",
)
raise HTTPException(
status_code=500, detail=f"Erreur serveur S3: {str(e)}"
)