article

Monday, February 6, 2023

FastAPI Jinja2 Upload multiple images and show images

FastAPI Jinja2 Upload multiple images and show images

Install Fastapi

https://github.com/tiangolo/fastapi

pip install fastapi
C:\fastAPI\multipleupload>pip install fastapi
C:\fastAPI\multipleupload>pip install "uvicorn[standard]"

Install sqlalchemy jinja2
pip install python-multipart sqlalchemy jinja2
C:\fastAPI\multipleupload>pip install python-multipart sqlalchemy jinja2

Create main.py
multipleupload/main.py
//multipleupload/main.py
from fastapi import FastAPI, Request, UploadFile, File
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles

from typing import List

IMAGEDIR = "images/"

app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.mount("/images", StaticFiles(directory="images"), name="images")

@app.get('/', response_class=HTMLResponse)
def home(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.post("/upload-files")
async def create_upload_files(request: Request, files: List[UploadFile] = File(...)):
    for file in files:
        contents = await file.read()
        #save the file
        with open(f"{IMAGEDIR}{file.filename}", "wb") as f:
            f.write(contents)

    show = [file.filename for file in files]

    #return {"Result": "OK", "filenames": [file.filename for file in files]}
    return templates.TemplateResponse("index.html", {"request": request, "show": show})
make templates inside the templates directory

multipleupload/templates/base.html
//multipleupload/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FastAPI Jinja2 Upload multiple images and show images - Cairocoders</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <h1 class="page-header text-center">FastAPI Jinja2 Upload multiple images and show images</h1>
    {% block content %}
        
    {% endblock content %}
</div>
</body>
</html>
multipleupload/templates/index.html
//multipleupload/templates/index.html
{% extends 'base.html' %}

{% block content %}
<div class="row">
	<form action="/upload-files/" enctype="multipart/form-data" method="post">
        <div class="mb-3">
            <label>Upload Files</label>
            <input class="form-control form-control-lg" name="files" type="file" multiple accept=".jpg, .png">
        </div>
        <div class="mb-3">
            <input type="submit" class="btn btn-primary btn-lg">
        </div>
	</form>
    <div class="col-12">
    {% for rs in show %}
        <div style="padding:20px;float:left;">
            <img width="500" src="{{ url_for('images', path=rs) }}">  
        </div>
    {% endfor %}  
    </div>
</div>    
{% endblock content %}
run the FastAPI app

C:\fastAPI\multipleupload>uvicorn main:app --reload
with uvicorn using the file_name:app_instance
open the link on the browser http://127.0.0.1:8000/
http://127.0.0.1:8000/docs

Related Post