article

Friday, July 23, 2021

Drag and Drop File Upload using DropzoneJS Python Flask PostgreSQL

Drag and Drop File Upload using DropzoneJS Python Flask PostgreSQL

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 uploads (
id serial PRIMARY KEY,
file_name VARCHAR ( 150 ) NOT NULL,
upload_time TIMESTAMP NOT NULL
);

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

https://www.dropzonejs.com/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#app.py
from flask import Flask, render_template, jsonify, request
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
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('index.html')
       
@app.route("/upload",methods=["POST","GET"])
def upload():
    cur = conn.cursor(cursor_factory=psycopg2.extras.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])
           conn.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/index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//templates/index.html
<html> 
 <head> 
  <title>Drag and Drop File Upload using DropzoneJS Python Flask PostgreSQL</title> 
<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>Drag and Drop File Upload using DropzoneJS Python Flask PostgreSQL</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