Open In App

Upload Multiple files with Flask

Last Updated : 04 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In online apps, uploading files is a common task. Simple HTML forms with encryption set to multipart/form information are all that is required to publish a file into a URL when using Flask for file upload. The file is obtained from the request object by the server-side flask script using the request. In this article, we will look at how to upload multiple files with Python. It allows the user to select multiple files at once and upload all files to the server. Before proceeding, Install the Flask by writing the command in the terminal:

pip install flask

Stepwise Implementation 

Step 1: Create a new project folder Upload. Inside this folder create main.py, and create folder templates.

Step 2: Create a simple HTML page index.html to select multiple files and submit them to upload files on the server. Here, the HTML file contains a form to select and upload files using the POST method. The enctype attribute plays an important role here. It specifies how the form data should be encoded when submitting it to the server. we are uploading files that’s why we should set the attribute value to multipart/form-data.

HTML




<html>
<head>
    <title>Upload Multiple files : GFG</title>
</head>
<body>
    <form action = "/upload" method="POST" enctype="multipart/form-data">
        <input type="file" name="file" multiple />
        <input type = "submit" value="Upload">
    </form>
</body>
</html>


Step 3: Now inside the main.py. Here the list of the file object is collected and then we will save the uploaded files one by one to the root directory using the loop and file.save() function.

Python3




from flask import *
app = Flask(__name__)
  
  
@app.route('/')
def main():
    return render_template("index.html")
  
  
@app.route('/upload', methods=['POST'])
def upload():
    if request.method == 'POST':
  
        # Get the list of files from webpage
        files = request.files.getlist("file")
  
        # Iterate for each file in the files List, and Save them
        for file in files:
            file.save(file.filename)
        return "<h1>Files Uploaded Successfully.!</h1>"
  
  
if __name__ == '__main__':
    app.run(debug=True)


Output:

Run the following command in Terminal

python main.py

Index Page

Select multiple files from your folder.

Select Multiple Images

After submitting, a Success message will displayed. 

Files Uploaded

Here we can see that four *.png images are uploaded to the root directory of a project.

Verification



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads