Flask Tutorials: File Upload Configuration

beginner
24 min

Flask Tutorials: File Upload Configuration

Welcome back to CodeYourCraft! Today, we're diving into a practical and exciting topic - File Upload Configuration using Flask. Let's get started!

Introduction 🎯

Flask is a micro web framework written in Python that makes it easy to build web applications. Today, we'll learn how to implement file uploads in a Flask application. This is a crucial skill for developing dynamic web applications that can handle user-generated content.

Why do we need File Upload Configuration in Flask? 💡

File uploads allow users to submit files as part of a form, which can be particularly useful for applications like image galleries, document management systems, and more. In this tutorial, we'll create a simple form for uploading files and learn how to handle those uploads in our Flask application.

Setting up the Environment 📝

Before we dive into the code, make sure you have the following prerequisites:

  • Python 3.x installed
  • Flask installed (pip install flask)

Creating the Application Structure ✅

First, let's create a new directory for our application:

bash
mkdir flask-file-upload cd flask-file-upload

Next, we'll create a basic file structure for our application:

bash
touch app.py mkdir templates touch templates/upload.html touch requirements.txt

Implementing the Upload Form 💡

Now, let's create an HTML template for our file upload form:

html
<!-- templates/upload.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>File Upload</title> </head> <body> <h1>Upload a file</h1> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <button type="submit">Upload</button> </form> </body> </html>

Connecting the Form to Flask 📝

Next, we'll write the Flask application code that handles our form and processes the uploaded file:

python
# app.py from flask import Flask, render_template, request, redirect, url_for from werkzeug.utils import secure_filename app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads' app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg'} if not os.path.exists(app.config['UPLOAD_FOLDER']): os.makedirs(app.config['UPLOAD_FOLDER']) def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS'] @app.route('/') def upload_form(): return render_template('upload.html') @app.route('/upload', methods=['POST']) def upload_file(): if 'file' not in request.files: return redirect(request.url) file = request.files['file'] 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 redirect(request.url) @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) if __name__ == '__main__': app.run(debug=True)

Testing the Application ✅

Now, let's run our application and test the file upload functionality:

bash
python app.py

Open your browser and navigate to http://127.0.0.1:5000/. You should see our file upload form. Try uploading a file to see the application in action!

Wrapping Up 📝

Congratulations! You've successfully implemented file uploads in a Flask application. Now that you've seen how easy it is to handle user-generated content, take some time to experiment with this example and improve it based on your needs.

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the `UPLOAD_FOLDER` configuration in our Flask application?