article

Thursday, December 17, 2020

jQuery Ajax Drag and Drop File Upload with Python Flask and MySQLdb


jQuery Ajax Drag and Drop File Upload with Python Flask and MySQLdb

In this tutorial you will learn how to implement drag and drop file upload using jQuery and Python Flask. 
We will use DropzoneJS jQuery plugin to handle drag and drop file upload functionality.

DropzoneJS is an open source library that provides drag’n’drop file uploads with image previews.

It’s lightweight, doesn’t depend on any other library (like jQuery) and is highly customizable.

www.dropzonejs.com
Download https://github.com/enyo/dropzone/archive/v5.7.0.zip

Create Database

CREATE TABLE `uploads` (
  `id` int(11) NOT NULL,
  `file_name` varchar(150) NOT NULL,
  `upload_time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
app.py
 
#app.py
from flask import Flask, render_template, jsonify, request
from flask_mysqldb import MySQL,MySQLdb #pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request
from datetime import datetime

app = Flask(__name__)
   
app.secret_key = "caircocoders-ednalan-2020"
   
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)
   
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
 
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
 
def allowed_file(filename):
 return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
@app.route('/')
def main():
    return render_template('drop_and_drop_upload.html')
     
@app.route("/upload",methods=["POST","GET"])
def upload():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)	
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
        now = datetime.now()
		
        if file and allowed_file(file.filename):
           file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

           cur.execute("INSERT INTO uploads (file_name, upload_time) VALUES (%s, %s)",[file.filename, now])
           mysql.connection.commit()
           cur.close()
           print('File successfully uploaded ' + file.filename + ' to the database!')
        else:
           print('Invalid Uplaod only txt, pdf, png, jpg, jpeg, gif') 
        msg = 'Success Uplaod'		
    return jsonify(msg)
	
if __name__ == '__main__':
    app.run(debug=True)
templates/drop_and_drop_upload.html
//templates/drop_and_drop_upload.html
<html>  
 <head>  
  <title>jQuery Ajax Drag and Drop File Upload with Python Flask and MySQLdb</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="/static/dropzone/dropzone.css" />
<script type="text/javascript" src="/static/dropzone/dropzone.js"></script>
 </head>  
 <body> 
<div class="container"> 
	<h2>jQuery Ajax Drag and Drop File Upload with Python Flask and MySQLdb</h2>
	<div class="dropzone">
		<div class="dz-message needsclick">
			<h1>Drop files here or click to upload.</h1>
		</div>
	</div>
</div>
<script>
$(document).ready(function(){
	$(".dropzone").dropzone({
	  url: '/upload',
	  width: 300,
	  height: 300, 
	  progressBarWidth: '100%',
	  maxFileSize: '5MB'
	})
});
</script>	
 </body>  
</html>   

Related Post