article

Tuesday, February 16, 2021

File Upload Progress Bar using Python Flask JQuery Ajax and MySQL Database

File Upload Progress Bar using Python Flask JQuery Ajax and MySQL Database

--
-- Table structure for table `uploads`
--

CREATE TABLE `uploads` (
  `id` int(11) NOT NULL,
  `file_name` varchar(150) NOT NULL,
  `upload_time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `uploads`
--

INSERT INTO `uploads` (`id`, `file_name`, `upload_time`) VALUES
(1, 'car.jpg', '2021-02-17 08:10:47');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `uploads`
--
ALTER TABLE `uploads`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `uploads`
--
ALTER TABLE `uploads`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX.


app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from werkzeug.utils import secure_filename
import os
from datetime import datetime

app = Flask(__name__)
        
app.secret_key = "caircocoders-ednalan"
        
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'testingdb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app) 

app.config['UPLOAD_FOLDER'] = 'static/uploads'
  
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
  
def allowed_file(filename):
 return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def index(): 
    return render_template('index.html')

@app.route("/upload",methods=["POST","GET"])
def upload():
    file = request.files['uploadFile']
    filename = secure_filename(file.filename)
    if file and allowed_file(file.filename):
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        filenameimage = file.filename

        today = datetime.today() 
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("INSERT INTO uploads (file_name,upload_time) VALUES (%s,%s)",[filenameimage,today])
        mysql.connection.commit()       
        cur.close()
        msg  = 'File successfully uploaded ' + file.filename + ' to the database!' 
    else:
        msg  = 'Invalid Uplaod only png, jpg, jpeg, gif' 
    return jsonify({'htmlresponse': render_template('response.html', msg=msg, filenameimage=filenameimage)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>File Upload Progress Bar using Python Flask JQuery Ajax and MySQL Database</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" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
<!--<script src="/static/js/jquery.form.js"></script>-->
</head>
	<body>
		<div class="container">
			<br />
			<h3 align="center">File Upload Progress Bar using Python Flask JQuery Ajax and MySQL Database</h3>
			<br />
			<div class="panel panel-default">
				<div class="panel-heading"><b>Ajax File Upload Progress Bar using JQuery Ajax</b></div>
				<div class="panel-body">
					<form id="uploadImage" action="/upload" method="post">
						<div class="form-group">
							<label>File Upload</label>
							<input type="file" name="uploadFile" id="uploadFile" accept=".jpg, .png" />
						</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 id="loader-icon" style="display:none;"><img src="/static/images/loader.gif" /></div>
				</div>
			</div>
		</div>
<script>
$(document).ready(function(){
	$('#uploadImage').submit(function(event){
		if($('#uploadFile').val()){
			event.preventDefault();
			$('#loader-icon').show();
			$('#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){
					$('#loader-icon').hide();
					$('#targetLayer').show();
					$('#targetLayer').append(data.htmlresponse);
				},
				resetForm: true
			});
		}
		return false;
	});
});
</script>
</body>
</html>
templates/response.html
//templates/response.html
<p><b>{{ msg }}</b></p>
<img src="/static/uploads/{{ filenameimage }}" class="img-thumbnail" width="300" height="250" />

Related Post