Python Flask MongoDB Upload File and validate before save to Database
app.py
#app.py
from flask import Flask, render_template, flash, redirect, url_for, request
from flask_mongoengine import MongoEngine #ModuleNotFoundError: No module named 'flask_mongoengine' = (venv) C:\flaskmyproject>pip install flask-mongoengine
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request
app = Flask(__name__)
app.secret_key = "caircocoders-ednalan-2020"
app.config['MONGODB_SETTINGS'] = {
'db': 'dbmongocrud',
'host': 'localhost',
'port': 27017
}
db = MongoEngine()
db.init_app(app)
UPLOAD_FOLDER = 'static/img'
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
class User(db.Document):
name = db.StringField()
email = db.StringField()
profile_pic = db.StringField()
@app.route('/')
def index():
return render_template('upload.html')
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['inputFile']
rs_username = request.form['txtusername']
inputEmail = request.form['inputEmail']
filename = secure_filename(file.filename)
if file and allowed_file(file.filename):
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
usersave = User(name=rs_username, email=inputEmail, profile_pic=file.filename)
usersave.save()
flash('File successfully uploaded ' + file.filename + ' to the database!')
return redirect('/')
else:
flash('Invalid Uplaod only txt, pdf, png, jpg, jpeg, gif')
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
templates/upload.html
//templates/upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Python Flask MongoDB Upload File and validate before save to Database</title>
</head>
<body>
<h2>Python Flask MongoDB Upload File and validate before save to Database </h2>
<h3>Select a file to upload</h3>
<p>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-primary">
<strong>{{ message }}</strong>
</div>
{% endfor %}
{% endif %}
{% endwith %}
</p>
<form method="post" action="/upload" enctype="multipart/form-data">
<p>Name : <input type="text" name="txtusername" value="" placeholder="User Name" required> </p>
<p>Email : <input type="email" name="inputEmail" placeholder="Email address" required></p>
<p>
<input type="file" name="inputFile" autocomplete="off" required onchange="loadFile(event)">
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
<img id="output" width="500"/>
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src)
}
};
</script>
<style>
.alert-primary {
color: #004085;
background-color: #cce5ff;
border-color: #b8daff;
}
.alert {
position: relative;
padding: .75rem 1.25rem;
margin-bottom: 1rem;
border: 1px solid transparent;
border-radius: .25rem;
}
</style>
</body>
</html>
VIDEO