article

Saturday, July 10, 2021

Upload Multiple Images using Python Flask PostgreSQL Database

Upload Multiple Images using Python Flask PostgreSQL Database

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE images (
id serial PRIMARY KEY,
file_name VARCHAR ( 100 ) NOT NULL,
uploaded_on TIMESTAMP
);
app.py
 
#app.py
from flask import Flask, render_template, redirect, request, flash
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request
from datetime import datetime
import psycopg2 #pip install psycopg2 
import psycopg2.extras
    
app = Flask(__name__)
    
app.secret_key = "caircocoders-ednalan"
    
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
        
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
 
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('/')
def index():
    return render_template('index.html')
 
@app.route("/upload",methods=["POST","GET"])
def upload():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    now = datetime.now()
    print(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])
                conn.commit()
            print(file)
        cur.close()   
        flash('File(s) successfully uploaded')    
    return redirect('/')
    
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
 <title>Upload Multiple Images using Python Flask PostgreSQL Database</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>Upload Multiple Images using Python Flask PostgreSQL Database</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