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
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
//templates/index.html
<html>
<head>
<title>Drag and Drop File Upload using DropzoneJS Python Flask PostgreSQL</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>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>
