1

I am trying to find a way to insert an image using FastAPI, this is my code:

app = FastAPI()

app.add_middleware(
CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
)

@app.get("/files/{file_path:path}")


def read_user_me(file_path: str):
html_content = """

<html>
    <head>
        <title>Some HTML in here</title>
    </head>
    <body>
        <img src="file:///Users/user/Desktop/document/app//{0}"></img>
    </body>
</html>

"""

html_content =  html_content.format(file_path,file_path)
return HTMLResponse(content=html_content, status_code=200)

When I start the univorn and open localhost. I receive the following error:

Not allowed to load local resource: file:///Users/user/Desktop/document/app//img.jpg

Please help

RalphCh97
  • 61
  • 9

1 Answers1

2

I'm assuming you're trying to serve static files, which is documented here (FastAPI) and here (Starlette).

In a more advanced setup (but common practice) you could serve static files (and user uploads) by setting up a proxy in front of your application (e.g. nginx, lighttpd, et cetera. which are optimised for these kind of requests).

Concerning security, using 'file:///Users/us...' exposes a lot about your os and filesystem to anyone with access to your website and potentially opens the door to things like XSS attacks. It's a bad idea.

Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100