Upload Multiple files with Flask
×


Upload Multiple files with Flask

998

Upload Multiple Files with Flask

Introduction

Uploading multiple files at once is a common feature in modern web applications. Flask, a lightweight Python framework, makes it easy to build this functionality. In this article, we’ll walk through how to handle multiple file uploads efficiently using Flask.

Setting Up Your Project

Begin by organizing your project structure as follows:

  • app.py – your main Flask application
  • templates/ – folder to hold your HTML files
  • uploads/ – directory to save uploaded files

Configuring Flask for Multiple File Uploads

Import the necessary modules and set up Flask configuration for file uploads, including allowed file extensions and upload folder location.

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

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024  # 32 MB limit

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'txt'}

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

Creating the Upload Route

This route will handle both rendering the upload form and processing the files uploaded via POST request.

@app.route('/', methods=['GET', 'POST'])
def upload_files():
    if request.method == 'POST':
        if 'files[]' not in request.files:
            return 'No files part in the request'
        files = request.files.getlist('files[]')
        saved_files = []
        for file in files:
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                saved_files.append(filename)
        return f'Successfully uploaded: {", ".join(saved_files)}'
    return render_template('upload_multiple.html')

HTML Form for Multiple File Upload

Create an HTML form that allows users to select and upload multiple files at once:

<!-- templates/upload_multiple.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Multiple Files</title>
</head>
<body>
    <h1>Upload Multiple Files</h1>
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="files[]" multiple required>
        <button type="submit">Upload Files</button>
    </form>
</body>
</html>

Key Considerations

  • Use multiple attribute on the input to enable selecting multiple files.
  • Always sanitize filenames with secure_filename for security.
  • Check file extensions to accept only safe and expected types.
  • Set a maximum upload size to protect your server from large file uploads.

Running the Flask Application

To start your Flask server, run:

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

Open http://127.0.0.1:5000/ in a browser to test uploading multiple files at once.

Conclusion

Uploading multiple files using Flask is straightforward when you handle file validation, security, and storage properly. This approach lets you enhance user experience by simplifying file submissions in your Python web applications.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat