article

Wednesday, January 13, 2021

Python Flask Upload Multiple Images and insert to database using mysqldb


Python Flask Upload Multiple Images and insert to database using mysqldb

Create Database Table

CREATE TABLE `images` (
  `id` int(11) NOT NULL,
  `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `uploaded_on` datetime NOT NULL,
  `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
app.py
 
#app.py
from flask import Flask, render_template, redirect, request, flash
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"
      
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
 
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('/',methods=["POST","GET"])
def index():
    return render_template('index.html')

@app.route("/upload",methods=["POST","GET"])
def upload():
    cursor = mysql.connection.cursor()
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    now = datetime.now()
    if request.method == 'POST':
        files = request.files.getlist('files[]')
        #print(files)
        for file in files:
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                cur.execute("INSERT INTO images (file_name, uploaded_on) VALUES (%s, %s)",[filename, now])
                mysql.connection.commit()
            print(file)
        cur.close()   
        flash('File(s) successfully uploaded')    
    return redirect('/')

if __name__ == "__main__":
    app.run(debug=True)
index.html
//index.html
<!DOCTYPE html>
<html>
<head>
 <title>Python Flask Upload Multiple Images and insert to database using mysqldb</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h2>Python Flask Upload Multiple Images and insert to database using mysqldb</h2>
    <div class="row">
        <div class="col-lg-12">
            <p>
                {% with messages = get_flashed_messages() %}
                  {% if messages %}
                 {% for message in messages %}
                   <div class="alert alert-success">
                    <strong>{{ message }}</strong>
                  </div>
                 {% endfor %}
                  {% endif %}
                {% endwith %}
               </p>
  <div>
   <!-- File upload form -->
   <form method="post" action="/upload" enctype="multipart/form-data" class="form-inline">
    <div class="form-group">
                      <label>Choose Images: </label>
                      <input type="file" name="files[]" id="fileInput" class="form-control" multiple >
                 </div>
                 <input type="submit" name="submit" class="btn btn-success" value="UPLOAD"/>
             </form>
  </div>
  </div>
 </div>
</div>
<script>
$(document).ready(function(){
 // File type validation
    $("#fileInput").change(function(){
        var fileLength = this.files.length;
        var match= ["image/jpeg","image/png","image/jpg","image/gif"];
        var i;
        for(i = 0; i < fileLength; i++){ 
            var file = this.files[i];
            var imagefile = file.type;
            if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]) || (imagefile==match[3]))){
                alert('Please select a valid image file (JPEG/JPG/PNG/GIF).');
                $("#fileInput").val('');
                return false;
            }
        }
    });
});
</script>
</body>
</html>

Related Post