Skip to content

Instantly share code, notes, and snippets.

@trohit
Created June 27, 2023 17:06
Show Gist options
  • Save trohit/c3a0cbb43db49fc85c98075c5f380514 to your computer and use it in GitHub Desktop.
Save trohit/c3a0cbb43db49fc85c98075c5f380514 to your computer and use it in GitHub Desktop.
upload a file using fastapi and jinja templates
https://stackoverflow.com/questions/73263202/how-to-display-uploaded-image-in-html-page-using-fastapi-jinja2
display.html
------------
<html>
<head>
<title>Display Uploaded Image</title>
</head>
<body>
<h1>My Image</h1>
<a href="/">Upload another image</a>
<img src="data:image/jpeg;base64,{{ myImage | safe }}">
</body>
</html>
index.html
----------
<html>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<label for="file">Choose image to upload</label>
<input type="file" id="files" name="file"><br>
<input type="submit" value="Upload">
</form>
</body>
</html>
#!/usr/bin/env python3
from fastapi import File, UploadFile, Request, FastAPI
from fastapi.templating import Jinja2Templates
import base64
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/")
def main(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.post("/upload")
def upload(request: Request, file: UploadFile = File(...)):
try:
contents = file.file.read()
with open("uploaded_" + file.filename, "wb") as f:
f.write(contents)
except Exception:
return {"message": "There was an error uploading the file"}
finally:
file.file.close()
base64_encoded_image = base64.b64encode(contents).decode("utf-8")
return templates.TemplateResponse("display.html", {"request": request, "myImage": base64_encoded_image})
<!--
path: templates/display.html
-->
<html>
<head>
<title>Display Uploaded Image</title>
</head>
<body>
<h1>My Image</h1>
<a href="/">Upload another image</a>
<img src="data:image/jpeg;base64,{{ myImage | safe }}">
</body>
</html>
<!--
path: templates/index.html
-->
<html>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<label for="file">Choose image to upload</label>
<input type="file" id="files" name="file"><br>
<input type="submit" value="Upload">
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment