Flask is a powerful and lightweight web framework for Python that allows you to build web applications with ease. One common requirement for web applications is the ability to upload files from users. In this beginner's guide, we'll explore how to implement file uploading in Flask using the Flask-Uploads extension. This will enable you to accept file uploads and process them in your Flask applications.

Prerequisites

Before we begin, ensure that you have the following set up on your system:

  • Python 3.6^ installed
  • A text editor or integrated development environment (IDE)
  • Basic knowledge of Python and Flask concepts

Step 1: Setting Up the Environment

Let's start by setting up a virtual environment for our Flask project. A virtual environment provides an isolated Python environment to work on your project. Open your command prompt or terminal and navigate to the project directory. Then, run the following commands:

  • On Linux/Mac:
python3 -m venv myenv  # Create a virtual environment
source myenv/bin/activate  # Activate the virtual environment
  • On Windows:
python -m venv myenv  # Create a virtual environment
myenv/bin/activate  # Activate the virtual environment

Step 2: Installing Flask and Flask-Uploads

With the virtual environment activated, we can install Flask and Flask-Uploads. Run the following command to install the required packages:

  • Installing Flask:
pip install flask
  • Installing Flask-Uploads:
pip install git+https://github.com/riad-azz/flask-uploads

We are using a github repository to install Flask-Uploads because as of version 0.2.1 there seem to be some import problems on the Pypi installer, if this is fixed in the future feel free to install using the usual command pip install Flask-Uploads.

Step 3: Creating the Flask Application

Now, let's create a Flask application. In your text editor or IDE, create a new Python file and name it app.py. Start by importing the necessary modules:

from flask import Flask, render_template, request
from flask_uploads import UploadSet, configure_uploads

Next, create an instance of the Flask class and set it to a variable called app and define an index route as our home page:

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

Step 4: Configuring Flask-Uploads

To handle file uploads, we need to configure Flask-Uploads. Add the following code after creating the app instance:

files = UploadSet('files', extensions=('txt', 'pdf', 'doc', 'docx'))
app.config['UPLOADED_FILES_DEST'] = 'uploads'
configure_uploads(app, files)

In the code above, we create an instance of UploadSet called files, specifying the allowed file extensions as a tuple. We set the UPLOADED_FILES_DEST configuration option to specify the folder where uploaded files will be stored. In this example, we use a folder named uploads.

Step 5: Creating the Upload Route

Let's define a route that handles file uploads. Add the following code after configuring Flask-Uploads:

@app.route('/upload', methods=['POST'])
def upload():
    if 'file' in request.files:
        filename = files.save(request.files['file'])
        file_url = files.url(filename)
        return f'Successfully uploaded the file {filename} : <a href="{file_url}">{file_url}</a>'
    else:
        return 'Upload failed, no file was included in the POST request'

In this code, we define a route named /upload. It accepts POST requests. If the request method is POST and a file named 'file' exists in the request files, we save the file using the files.save() function. Finally, if the save was successful we return a success message containing the uploaded file's name and URL else we return an error message.

Step 6: Creating the HTML Form

To allow users to upload files, we need to create an HTML form. In your project directory, create a folder named templates. Inside the templates folder, create an HTML file named index.html. Add the following code to index.html:

<!DOCTYPE html>
<html>
  <head>
    <title>File Upload</title>
  </head>
  <body>
    <h1>Upload a File</h1>
    <form method="POST" action="/upload" enctype="multipart/form-data">
      <input type="file" name="file" />
      <input type="submit" value="Upload" />
    </form>
  </body>
</html>

This HTML form contains an input element of type file for selecting the file to upload. The form's action attribute is set to /upload, matching the route we defined in the Flask app.

Step 7: Running the Flask App

Save all the changes you made to app.py and index.html. Your app.py should look like this by now:

from flask import Flask, render_template, request
from flask_uploads import UploadSet, configure_uploads

app = Flask(__name__)

files = UploadSet('files', extensions=('txt', 'pdf', 'doc', 'docx', "jpg"))
app.config['UPLOADED_FILES_DEST'] = 'uploads'
configure_uploads(app, files)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/upload', methods=['POST'])
def upload():
    if 'file' in request.files:
        filename = files.save(request.files['file'])
        file_url = files.url(filename)
        return f'Successfully uploaded the file {filename} : <a href="{file_url}">{file_url}</a>'
    else:
        return 'Upload failed, no file was included in the POST request'


if __name__ == "__main__":
    app.run()

Now, it's time to run the Flask app. In your terminal or command prompt, navigate to your project directory and run the following command:

python app.py

The Flask development server will start running, and you can access your app by visiting http://localhost:5000 in your web browser.

Conclusion

Congratulations! You have successfully implemented file uploading in Flask using Flask-Uploads. Users can now upload files through your web application. This guide covered the essential steps, from setting up the environment to handling file uploads and creating an HTML form.

Feel free to explore additional features provided by Flask-Uploads, such as file validation, renaming, and storage customization, to enhance your file upload functionality.