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
 
#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
//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>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>
</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
//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
//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