Trival File Upload Example From Flask Site
# https://flask.palletsprojects.com/en/2.3.x/patterns/fileuploads/ import os from flask import Flask, flash, request, redirect, url_for, send_from_directory from flask import get_flashed_messages from werkzeug.utils import secure_filename import secrets # Location of uploaded files, and legal upload extensions. UPLOAD_FOLDER = "/tmp/uploads" ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} # Create app and configure that upload location app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.secret_key = secrets.token_bytes() # Helper to check the file name extension against the permitted list. def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS # Very simple upload view and processor. @app.route('/', methods=['GET', 'POST']) def upload_file(): # See if we're handling a POST (file transmission in this case). if request.method == 'POST': # check if the post request has a file entry called myfile if 'myfile' not in request.files: flash('No file part') return redirect(request.url) # Get the object controlling the uploaded file data. file = request.files['myfile'] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == '': flash('No selected file') return redirect(request.url) # File was submitted, and name had an legal ending. if file and allowed_file(file.filename): # Get the file name, make it saft to use, and save the file # in its final location using the file object. filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('download_file', name=filename)) else: flash('Forbidden extension') err = '' if len(get_flashed_messages()) > 0: err="<p class='red'>"+"<br>".join(get_flashed_messages())+"</p>"; return ''' <!doctype html> <html> <head> <title>Upload new File</title> <style> h1 { font-family: sans; } .red { color: red; } </style> </head> <body> <h1>Upload new File</h1> <form method="post" enctype="multipart/form-data"> <input type="file" name="myfile"> <input type="submit" value="Upload"> </form>%s </body> </html> ''' % err @app.route('/uploads/<name>') def download_file(name): return send_from_directory(app.config["UPLOAD_FOLDER"], name)