fix: add upload images #50
+31
-16
@@ -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")
|
||||
|
||||
file_path = STORAGE_DIR / file.filename
|
||||
mime = magic.Magic(mime=True)
|
||||
content_type = mime.from_buffer(body)
|
||||
|
||||
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:
|
||||
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)
|
||||
|
||||
return {"status": "success", "filename": file.filename}
|
||||
random_filename = f"{uuid.uuid4()}.webp"
|
||||
file_path = STORAGE_DIR / random_filename
|
||||
|
||||
img.save(file_path, format="WEBP", quality=80)
|
||||
|
||||
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)
|
||||
@@ -1,3 +1,5 @@
|
||||
fastapi
|
||||
uvicorn
|
||||
python-multipart
|
||||
python-magic
|
||||
Pillow
|
||||
Reference in New Issue
Block a user