Created
February 24, 2019 13:23
-
-
Save yassineAlouini/28a7f5e8879f2f37377f382e8e255b59 to your computer and use it in GitHub Desktop.
Upload an image using Flask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from flask import Flask, redirect, render_template, request, url_for | |
from werkzeug.utils import secure_filename | |
DATA_FOLDER_PATH = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'static') | |
ALLOWED_EXTENSIONS = set(['.png', '.jpg', '.jpeg']) | |
IMG_MAX_SIZE = 16 * 1024 * 1024 | |
app = Flask(__name__) | |
app.config['UPLOAD_FOLDER'] = DATA_FOLDER_PATH | |
app.config['MAX_CONTENT_LENGTH'] = IMG_MAX_SIZE | |
def _is_allowed_file(filename): | |
return any(extension in filename.lower() for extension in ALLOWED_EXTENSIONS) | |
@app.route('/upload', methods=['GET', 'POST']) | |
def upload_img(): | |
""" Upload an image and redirect to the recognition route. """ | |
# Inspired from this: # http://flask.pocoo.org/docs/0.12/patterns/fileuploads/#uploading-files | |
if request.method == 'POST': | |
f = request.files['file'] | |
if f and _is_allowed_file(f.filename): | |
filename = secure_filename(f.filename) | |
img_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) | |
f.save(img_path) | |
return redirect(url_for('rec_img', filename=filename)) | |
else: | |
return "Try another image." | |
else: | |
return render_template('upload.html') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment