Files
backend/file-service/python/main.py
T
TakahashiNguyen c6683b28dc
Release package / release (push) Successful in 17m59s
fix: add upload images (#50)
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #50
2026-05-10 14:10:20 +00:00

53 lines
1.4 KiB
Python

import uuid
import io
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import FileResponse
from pathlib import Path
from PIL import Image
import filetype
app = FastAPI()
STORAGE_DIR = Path("images")
STORAGE_DIR.mkdir(exist_ok=True)
@app.post("/")
async def upload_image(request: Request):
body = await request.body()
if not body:
raise HTTPException(status_code=400, detail="Dữ liệu trống")
kind = filetype.guess(body)
if kind is None or not kind.mime.startswith("image/"):
mime_type = kind.mime if kind else "không xác định"
raise HTTPException(
status_code=400, detail=f"Định dạng {mime_type} không được hỗ trợ"
)
try:
img = Image.open(io.BytesIO(body))
random_filename = f"{uuid.uuid4()}.webp"
file_path = STORAGE_DIR / random_filename
img.save(file_path, format="WEBP", quality=80)
return {
"status": "success",
"filename": random_filename,
"original_type": kind.mime,
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Lỗi xử lý ảnh: {str(e)}")
@app.get("/{name}")
async def get_image(name: str):
file_path = STORAGE_DIR / name
if not file_path.exists():
raise HTTPException(status_code=404, detail="NotFoundImage")
return FileResponse(file_path, media_type="image/webp")