Flask Tutorials: Files Upload (request.files)

beginner
7 min

Flask Tutorials: Files Upload (request.files)

Welcome to the Files Upload tutorial using Flask! In this lesson, you will learn how to handle file uploads in your Flask applications. This skill is essential when building dynamic websites that require user-generated content.

Before diving into the code, let's discuss the request.files module in Flask that we'll be using for handling file uploads. šŸ’” Remember, request is a built-in object in Flask that contains information about the HTTP request.

What is request.files?

request.files is a dictionary-like object that enables access to uploaded files in a Flask application. It allows you to work with files directly, saving them to a local directory, moving them, or even processing them on the fly.

Setting up the Project

To get started, ensure you have Flask installed on your machine. If you haven't installed it yet, you can do so by running:

bash
pip install flask

Now, let's create a simple Flask application with a file upload form.

Step 1: Create a new Flask project

Create a new folder for your Flask project, and navigate to it in your terminal.

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

Step 2: Create the main application file

Create a new Python file called app.py:

bash
touch app.py

Step 3: Write the Flask application code

Open app.py and add the following code:

python
from flask import Flask, render_template, request from os import path app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads' if not path.exists(app.config['UPLOAD_FOLDER']): path.mkdir(app.config['UPLOAD_FOLDER']) @app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files['file'] if file: filename = file.filename file.save(path.join(app.config['UPLOAD_FOLDER'], filename)) return f'File {filename} uploaded successfully!' return render_template('upload_form.html') @app.route('/success') def success(): return 'File has been uploaded successfully!' if __name__ == '__main__': app.run(debug=True)

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

Step 4: Create the HTML form

Create a new folder called templates, and inside it, create a new HTML file called upload_form.html:

bash
mkdir templates touch templates/upload_form.html

Add the following code to upload_form.html:

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

Step 5: Run the Flask application

In your terminal, run the following command:

bash
python app.py

Now, open your browser and navigate to http://127.0.0.1:5000/. You should see a simple file upload form. Upload a file, and you'll see a success message!

šŸ“ Note: The app.config['UPLOAD_FOLDER'] is the directory where uploaded files will be saved.

Handling Multiple Files

To handle multiple files at once, modify the upload_file function in app.py as follows:

python
if request.method == 'POST': files = request.files.getlist('file[]') for file in files: filename = file.filename file.save(path.join(app.config['UPLOAD_FOLDER'], filename)) return f'Files uploaded successfully!'

With this change, the upload_file function can now handle multiple files at once.

Real-world Application

In a real-world scenario, you can use this feature to allow users to upload images, documents, or other files to your Flask application, making it more interactive and engaging!

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of the request.files module in Flask?