chore: update

This commit is contained in:
TakahashiNg
2026-05-10 10:55:52 +00:00
parent 877d0a92e1
commit 5cad8e6f7b
2 changed files with 35 additions and 18 deletions
+32 -17
View File
@@ -1,8 +1,10 @@
import os import uuid
import shutil import io
from fastapi import FastAPI, File, UploadFile, HTTPException import magic
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import FileResponse from fastapi.responses import FileResponse
from pathlib import Path from pathlib import Path
from PIL import Image
app = FastAPI() app = FastAPI()
@@ -10,25 +12,38 @@ STORAGE_DIR = Path("images")
STORAGE_DIR.mkdir(exist_ok=True) STORAGE_DIR.mkdir(exist_ok=True)
@app.post("/") @app.post("/")
async def upload_image(file: UploadFile = File(...)): async def upload_image(request: Request):
if not file.content_type.startswith("image/"): body = await request.body()
raise HTTPException(status_code=400, detail="Chỉ chấp nhận file ảnh.") 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 if not content_type.startswith("image/"):
raise HTTPException(status_code=400, detail=f"Định dạng không hỗ trợ: {content_type}")
# Ghi file theo kiểu stream để tránh tràn RAM
try: try:
with file_path.open("wb") as buffer: img_data = io.BytesIO(body)
shutil.copyfileobj(file.file, buffer) img = Image.open(img_data)
finally:
file.file.close() 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}") @app.get("/{name}")
async def get_image(name: str): async def get_image(name: str):
file_path = STORAGE_DIR / name file_path = STORAGE_DIR / name
if not file_path.exists() or not file_path.is_file(): if not file_path.exists():
raise HTTPException(status_code=404, detail="Không tìm thấy ảnh") raise HTTPException(status_code=404, detail="NotFoundImage")
return FileResponse(file_path) return FileResponse(file_path)
+3 -1
View File
@@ -1,3 +1,5 @@
fastapi fastapi
uvicorn uvicorn
python-multipart python-multipart
python-magic
Pillow