article

Sunday, February 5, 2023

FastAPI File Upload with Jinja2 Template

FastAPI File Upload with Jinja2 Template

Install Fastapi

https://github.com/tiangolo/fastapi

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

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

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

IMAGEDIR = "images/"

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

@app.get('/file-upload', response_class=HTMLResponse)
def get_basic_form(request: Request):
    return templates.TemplateResponse("form.html", {"request": request})

@app.post('/file-upload', response_class=HTMLResponse)
async def post_basic_form(request: Request, username: str = Form(...), password: str = Form(...), file: UploadFile = File(...)):
    print(f'username: {username}')
    print(f'password: {password}')
    print(f'Filename: {file.filename}')
    
    contents = await file.read()
    
    #save the file
    with open(f"{IMAGEDIR}{file.filename}", "wb") as f:
        f.write(contents)

    return templates.TemplateResponse("form.html", {"request": request})
make templates inside the templates directory

uploadfile/form.html
//uploadfile/form.html
<html>
<head>
<title>FastAPI File Upload with Jinja2 Template</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
<link rel="stylesheet" href="{{ url_for('static', path='css/main.css') }}">
</head>
<body>
<div class="container">
	<div class="row main">
		<div class="panel-heading">
	        <div class="panel-title text-center">
	            <h1 class="title">FastAPI File Upload with Jinja2 Template</h1>
	            <hr />
	        </div>
	    </div> 
		<div class="main-login main-center">
            <form class="form-horizontal" method="POST" enctype="multipart/form-data">
				<div class="form-group">
					<label for="name" class="cols-sm-2 control-label">Your Name</label>
					<div class="cols-sm-10">
						<div class="input-group">
							<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
							<input type="text" class="form-control" name="name" id="name"  placeholder="Enter your Name"/>
						</div>
					</div>
				</div>
                <div class="form-group">
					<label for="email" class="cols-sm-2 control-label">Your Email</label>
					<div class="cols-sm-10">
						<div class="input-group">
							<span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
							<input type="text" class="form-control" name="email" id="email"  placeholder="Enter your Email"/>
						</div>
					</div>
				</div>
                <div class="form-group">
					<label for="username" class="cols-sm-2 control-label">Username</label>
					<div class="cols-sm-10">
						<div class="input-group">
							<span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>
							<input type="text" class="form-control" name="username" id="username"  placeholder="Enter your Username"/>
						</div>
					</div>
				</div>
                <div class="form-group">
					<label for="password" class="cols-sm-2 control-label">Password</label>
					<div class="cols-sm-10">
						<div class="input-group">
							<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
							<input type="password" class="form-control" name="password" id="password"  placeholder="Enter your Password"/>
						</div>
					</div>
				</div>
                <div class="form-group">
					<label for="confirm" class="cols-sm-2 control-label">Upload File</label>
						<div class="cols-sm-10">
							<div class="input-group">
							<input type="file" name="file" class="form-control">
						</div>
					</div>
				</div>
                <div class="form-group ">
                    <input type="submit" value="Register" class="btn btn-primary btn-lg btn-block login-button">
				</div>
			</form>
	    </div>
    </div>
</div>  
</body>
</html>
uploadfile/static/css/main.css
//uploadfile/static/css/main.css
body, html{
    height: 100%;
    background-repeat: no-repeat;
    background-color: #d3d3d3;
    font-family: 'Oxygen', sans-serif;
}
.main{
    margin-top: 70px;
}
h1.title { 
   font-size: 50px;
   font-family: 'Passion One', cursive; 
   font-weight: 400; 
}
hr{
   width: 10%;
   color: #fff;
}
.form-group{
   margin-bottom: 15px;
}
label{
   margin-bottom: 15px;
}
input,
input::-webkit-input-placeholder {
   font-size: 12px;
   padding-top: 3px;
}
.main-login{
    background-color: #fff;
   -moz-border-radius: 2px;
   -webkit-border-radius: 2px;
   border-radius: 2px;
   -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
   -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
   box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);

}
.main-center{
    margin-top: 30px;
    margin: 0 auto;
    max-width: 500px;
   padding: 40px 40px;
}
.login-button{
   margin-top: 5px;
}
.login-register{
   font-size: 12px;
   text-align: center;
}
uploadfile/static/css/main.css run the FastAPI app

C:\fastAPI\uploadfile>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