Handling File Uploads With Flask - miguelgrinberg.com


Tue Sep 06 2022 13:11:41 GMT+0000 (UTC)

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

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'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def index():
    return render_template('index.html')

@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']:
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return redirect(url_for('index'))

As you see in the examples, no matter how complicated or malicious the filename is, the secure_filename() function reduces it to a flat filename. Let's incorporate secure_filename() into the example upload server, and also add a configuration variable that defines a dedicated location for file uploads. Here is the complete app.py source file with secure filenames: