feat: upload file nella cartella IMAGES_DIR
POST /upload_to_folder: sanitizza nome, valida estensione e contenuto via cv2.imdecode, auto-rename su collisione. Toolbar UI: bottone 'Carica file', dopo upload ricarica picker. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -329,6 +329,49 @@ def index():
|
||||
return HTMLResponse(html_path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@app.post("/upload_to_folder")
|
||||
async def upload_to_folder(file: UploadFile = File(...)):
|
||||
"""Salva file caricato nella cartella IMAGES_DIR. Ritorna lista aggiornata."""
|
||||
if not IMAGES_DIR.is_dir():
|
||||
raise HTTPException(500, f"IMAGES_DIR non esiste: {IMAGES_DIR}")
|
||||
# Sanitizza nome file (no traversal)
|
||||
name = Path(file.filename or "upload.png").name
|
||||
if not name:
|
||||
raise HTTPException(400, "nome file vuoto")
|
||||
ext = Path(name).suffix.lower()
|
||||
allowed = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff"}
|
||||
if ext not in allowed:
|
||||
raise HTTPException(400, f"estensione non supportata: {ext}")
|
||||
# Leggi contenuto e valida come immagine
|
||||
data = await file.read()
|
||||
arr = np.frombuffer(data, dtype=np.uint8)
|
||||
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
|
||||
if img is None:
|
||||
raise HTTPException(400, "file non è un'immagine valida")
|
||||
# Evita overwrite: se esiste, aggiungi suffisso numerico
|
||||
target = IMAGES_DIR / name
|
||||
if target.exists():
|
||||
stem = target.stem; suffix = target.suffix
|
||||
i = 1
|
||||
while True:
|
||||
alt = IMAGES_DIR / f"{stem}_{i}{suffix}"
|
||||
if not alt.exists():
|
||||
target = alt; break
|
||||
i += 1
|
||||
# Scrivi su disco
|
||||
with open(target, "wb") as f:
|
||||
f.write(data)
|
||||
# Ritorna lista aggiornata
|
||||
return {
|
||||
"saved_as": target.name,
|
||||
"dir": str(IMAGES_DIR),
|
||||
"files": sorted(
|
||||
p.name for p in IMAGES_DIR.iterdir()
|
||||
if p.is_file() and p.suffix.lower() in allowed
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/folder_image/{filename}")
|
||||
def folder_image(filename: str, w: int = 120):
|
||||
"""Serve thumbnail PNG dell'immagine IMAGES_DIR (scalata a width w)."""
|
||||
|
||||
Reference in New Issue
Block a user