To handle uploading and downloading files in a Flask web application, you need to set up routes that can handle file uploads from users and serve files for users to download.
Here is a basic example that illustrates both of these processes:
Before you begin, ensure you have Flask installed. If you don't have Flask installed, you can install it using pip:
pip install Flask
import os from flask import Flask, request, redirect, url_for, send_from_directory from werkzeug.utils import secure_filename UPLOAD_FOLDER = '/path/to/the/uploads' # Replace with your desired upload directory ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: return redirect(request.url) file = request.files['file'] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == '': return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('uploaded_file', filename=filename)) return ''' <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form method=post enctype=multipart/form-data> <input type=file name=file> <input type=submit value=Upload> </form> '''
@app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
To allow users to download files, you can use the send_from_directory
function that Flask provides:
@app.route('/download/<filename>') def download_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
The as_attachment=True
parameter will prompt the browser to download the file rather than displaying it.
Don't forget to run the Flask app at the end of your script:
if __name__ == '__main__': app.run(debug=True)
UPLOAD_FOLDER
should be a directory on your server where uploaded files will be stored. This directory must be writable by the user that runs the Flask application.ALLOWED_EXTENSIONS
set defines which file extensions are allowed to be uploaded. Adjust it according to your needs.secure_filename
function from Werkzeug is used to sanitize the filename before storing it on the filesystem.When allowing file uploads, you should be very careful:
This example is very basic and serves to illustrate the concept. For a production environment, you'll need to handle exceptions, provide user feedback, and implement additional security measures.
dalvik apache-spark-2.0 periodicity oauth-2.0 sum fuzzyjoin sharepoint windows-server-2008 breakpoints mpmovieplayercontroller