article

Sunday, February 5, 2023

FastAPI Jinja2 File Upload Progress Bar using JQuery Ajax

FastAPI Jinja2 File Upload Progress Bar using JQuery Ajax

Install Fastapi

https://github.com/tiangolo/fastapi

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

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

Create main.py
uploadajax/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
#uploadajax/main.py
from typing import Union
 
from fastapi import FastAPI, Request, UploadFile, File
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
 
IMAGEDIR = "images/"
 
app = FastAPI()
templates = Jinja2Templates(directory="templates")
 
@app.get('/', response_class=HTMLResponse)
def home(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})
 
@app.post('/uploadfile', response_class=HTMLResponse)
async def post_basic_form(request: Request, file: UploadFile = File(...)):
    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('success.html', context={'request': request})
make templates inside the templates directory

The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX.
https://github.com/jquery-form/form

uploadajax/templates/base.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//uploadajax/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 File Upload Progress Bar using JQuery Ajax - Cairocoders</title>
</head>
<body>
<div class="container">
    <h1 class="page-header text-center">FastAPI Jinja2 File Upload Progress Bar using JQuery Ajax</h1>
    {% block content %}
         
    {% endblock content %}
</div>
</body>
</html>
uploadajax/templates/index.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
//uploadajax/templates/index.html
{% extends 'base.html' %}
 
{% block content %}
    <div class="panel panel-default" style="margin-top: 50px;">
        <div class="panel-heading"><b>FastAPI Jinja2 File Upload Progress Bar using JQuery Ajax</b></div>
        <div class="panel-body">
            <form id="uploadImage" method="post" action="/uploadfile" enctype="multipart/form-data">
                <div class="form-group">
                    <label>File Upload</label>
                    <input type="file" name="file" multiple="true" id="file" />
                </div>
                <div class="form-group">
                    <input type="submit" id="uploadSubmit" value="Upload" class="btn btn-info" />
                </div>
                <div class="progress">
                    <div class="progress-bar progress-bar-striped bg-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
                <div id="targetLayer" style="display:none;"></div>
            </form>
        </div>
    </div>
<script>
$(document).ready(function(){
$('#uploadImage').submit(function(event){
    if($('#file').val()){
        event.preventDefault();
        $('#targetLayer').hide();
        $(this).ajaxSubmit({
            target: '#targetLayer',
            beforeSubmit:function(){
                $('.progress-bar').width('50%');
            },
            uploadProgress: function(event, position, total, percentageComplete)
            {
                $('.progress-bar').animate({
                    width: percentageComplete + '%'
                }, {
                    duration: 1000
                });
            },
            success:function(data){ //alert(data);
                $('#targetLayer').show();
                $('#targetLayer').append(data.htmlresponse);
            },
            resetForm: true
        });
    }
    return false;
});
});
</script>
{% endblock content %}
uploadajax/templates/success.html
1
2
//uploadajax/templates/success.html
<h4>File successfully uploaded to /images!</h4>
run the FastAPI app

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