Files
backend/file-service/python/main.py
T
2026-05-08 09:23:52 +00:00

35 lines
1.2 KiB
Python

import os
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import FileResponse
from pathlib import Path
app = FastAPI()
# Thư mục lưu trữ ảnh (nên được mount volume khi chạy docker)
STORAGE_DIR = Path("images")
STORAGE_DIR.mkdir(exist_ok=True)
@app.post("/")
async def upload_image(file: UploadFile = File(...)):
# Chỉ chấp nhận định dạng ảnh
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File không hợp lệ. Chỉ chấp nhận ảnh.")
file_path = STORAGE_DIR / file.filename
# Ghi file theo block để tối ưu bộ nhớ
with open(file_path, "wb") as f:
content = await file.read()
f.write(content)
return {"status": "success", "filename": file.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")
# Trả về ảnh trực tiếp cho trình duyệt/client
return FileResponse(file_path)