Handling File Uploads With Flask - miguelgrinberg.com


Tue Sep 06 2022 14:21:28 GMT+0000 (UTC)

Saved by @Rmin #python #flask #validation #uploadfile

import imghdr
import os
from flask import Flask, render_template, request, redirect, url_for, abort, \
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def validate_image(stream):
    header = stream.read(512)
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')

def too_large(e):
    return "File is too large", 413

def index():
    files = os.listdir(app.config['UPLOAD_PATH'])
    return render_template('index.html', files=files)

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            return "Invalid image", 400
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return '', 204

def upload(filename):
    return send_from_directory(app.config['UPLOAD_PATH'], filename)

Here is the complete and updated version of app.py designed to work with dropzone.js: