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 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)
+3 -1
View File
@@ -1,3 +1,5 @@
fastapi
uvicorn
python-multipart
python-multipart
python-magic
Pillow