Files
backend/file-service/python/main.py
T
TakahashiNguyen 4290f482f4
Release package / release (push) Successful in 1m49s
fix: better getCart (#49)
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #49
2026-05-11 07:27:14 +00:00

45 lines
1.2 KiB
Python

import uuid
import io
from fastapi import FastAPI, File, UploadFile, 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(file: UploadFile = File(...)):
body = await file.read()
kind = filetype.guess(body)
if not kind or not kind.mime.startswith("image/"):
raise HTTPException(status_code=400, detail="Chỉ chấp nhận file ảnh.")
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 {
"filename": random_filename,
}
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")