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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//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="{{ 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//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