File size: 667 Bytes
45392c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
import os

app = FastAPI()

BASE_IMAGE_DIR = "images"


@app.get("/images/{file_path:path}")
def get_image(file_path: str):
    # Chuẩn hóa đường dẫn, tránh ../
    # Ghép path rồi chuyển sang absolute
    full_path = os.path.abspath(os.path.join(BASE_IMAGE_DIR, file_path))

    # Chặn path traversal
    if not full_path.startswith(os.path.abspath(BASE_IMAGE_DIR)):
        raise HTTPException(403, "Forbidden")

    if not os.path.isfile(full_path):
        raise HTTPException(404, "Image not found")

    return FileResponse(full_path)