diff --git a/file-service/python/main.py b/file-service/python/main.py index c6e3938..a7e6abc 100644 --- a/file-service/python/main.py +++ b/file-service/python/main.py @@ -1,8 +1,10 @@ -import os -import shutil -from fastapi import FastAPI, File, UploadFile, HTTPException +import uuid +import io +import magic +from fastapi import FastAPI, Request, HTTPException from fastapi.responses import FileResponse from pathlib import Path +from PIL import Image app = FastAPI() @@ -10,25 +12,38 @@ STORAGE_DIR = Path("images") STORAGE_DIR.mkdir(exist_ok=True) @app.post("/") -async def upload_image(file: UploadFile = File(...)): - if not file.content_type.startswith("image/"): - raise HTTPException(status_code=400, detail="Chỉ chấp nhận file ảnh.") +async def upload_image(request: Request): + body = await request.body() + if not body: + raise HTTPException(status_code=400, detail="Body trống") + + mime = magic.Magic(mime=True) + content_type = mime.from_buffer(body) - file_path = STORAGE_DIR / file.filename - - # Ghi file theo kiểu stream để tránh tràn RAM + if not content_type.startswith("image/"): + raise HTTPException(status_code=400, detail=f"Định dạng không hỗ trợ: {content_type}") + try: - with file_path.open("wb") as buffer: - shutil.copyfileobj(file.file, buffer) - finally: - file.file.close() + img_data = io.BytesIO(body) + img = Image.open(img_data) + + random_filename = f"{uuid.uuid4()}.webp" + file_path = STORAGE_DIR / random_filename + + img.save(file_path, format="WEBP", quality=80) - return {"status": "success", "filename": file.filename} + except Exception as e: + raise HTTPException(status_code=500, detail=f"Lỗi xử lý ảnh: {str(e)}") + + return { + "status": "success", + "original_format": content_type, + "filename": random_filename + } @app.get("/{name}") async def get_image(name: str): file_path = STORAGE_DIR / name - if not file_path.exists() or not file_path.is_file(): - raise HTTPException(status_code=404, detail="Không tìm thấy ảnh") - + if not file_path.exists(): + raise HTTPException(status_code=404, detail="NotFoundImage") return FileResponse(file_path) \ No newline at end of file diff --git a/file-service/python/requirements.txt b/file-service/python/requirements.txt index 6d7503c..239d8f6 100644 --- a/file-service/python/requirements.txt +++ b/file-service/python/requirements.txt @@ -1,3 +1,5 @@ fastapi uvicorn -python-multipart \ No newline at end of file +python-multipart +python-magic +Pillow \ No newline at end of file