Handling File Uploads in Flask


In this tutorial, we will learn how to handle file uploads in Flask. We will cover configuring file upload settings and securely handling file uploads with real examples.

Step 1: Setting Up Flask

Install Flask using pip if you don’t already have it:

pip install flask

Create a new Python file, for example, app.py, and import the required modules:

    from flask import Flask, render_template, request, redirect, url_for
    import os
    from werkzeug.utils import secure_filename
        

Step 2: Configuring File Upload Settings

Configure your Flask app to handle file uploads. Add the following configuration to app.py:

    app = Flask(__name__)

    # Configure the upload folder
    UPLOAD_FOLDER = 'uploads'
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

    # Allow only specific file extensions
    ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

    # Create the upload folder if it doesn't exist
    os.makedirs(UPLOAD_FOLDER, exist_ok=True)

    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
        

Here, we define a function allowed_file to ensure only certain file types are allowed.

Step 3: Handling File Uploads

Create a route to render the upload form and handle file uploads:

    @app.route('/', methods=['GET', 'POST'])
    def upload_file():
        if request.method == 'POST':
            # Check if the POST request has a file part
            if 'file' not in request.files:
                return 'No file part'

            file = request.files['file']

            # If no file is selected
            if file.filename == '':
                return 'No selected file'

            # Check if the file is allowed
            if file and allowed_file(file.filename):
                # Secure the filename
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                return f'File uploaded successfully: {filename}'
        
        return render_template('upload.html')
        

Create an upload.html file in the templates folder to render the form:

    
    
    
        File Upload
    
    
        

Upload a File

Step 4: Running the Application

Run your Flask app:

python app.py

Navigate to http://127.0.0.1:5000 in your browser. Use the form to upload a file. If successful, the file will be saved in the uploads folder.

Step 5: Securely Handling File Uploads

To enhance security, follow these best practices:

  • Use secure_filename to sanitize filenames.
  • Restrict uploads to specific file extensions using the ALLOWED_EXTENSIONS set.
  • Store files in a dedicated folder with restricted access.
  • Scan uploaded files for malware if necessary.

Complete Example

Here is the complete app.py file:

    from flask import Flask, render_template, request, redirect, url_for
    import os
    from werkzeug.utils import secure_filename

    app = Flask(__name__)

    UPLOAD_FOLDER = 'uploads'
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
    os.makedirs(UPLOAD_FOLDER, exist_ok=True)

    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

    @app.route('/', methods=['GET', 'POST'])
    def upload_file():
        if request.method == 'POST':
            if 'file' not in request.files:
                return 'No file part'
            file = request.files['file']
            if file.filename == '':
                return 'No selected file'
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                return f'File uploaded successfully: {filename}'
        return render_template('upload.html')

    if __name__ == '__main__':
        app.run(debug=True)
        

Conclusion

In this tutorial, we learned how to handle file uploads in Flask, configure upload settings, and securely process uploaded files. These techniques are essential for building applications that require file handling features.





Advertisement