# Code lifted from this simple tutorial: # 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" UPLOAD_FOLDER = "/home/bennet/courses/cs445/flask/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 file from the request. Flask (or wsgi) saved the data # somewhere. This returns a descriptive object file = request.files['myfile'] # No file was actually submitted through the form. 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="

"+"
".join(get_flashed_messages())+"

"; return ''' Upload new File

Upload new File

%s ''' % err # This handles the "upload" link, which simply directs the browser # to a given file. @app.route('/uploads/') def download_file(name): return send_from_directory(app.config["UPLOAD_FOLDER"], name)