Files
backend/file-service/python/main.py
T
2026-05-10 01:55:37 +00:00

34 lines
1.0 KiB
Python

import os
import shutil
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import FileResponse
from pathlib import Path
app = FastAPI()
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.")
file_path = STORAGE_DIR / file.filename
# 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()
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")
return FileResponse(file_path)