Flask – Upload Multiple Files


I am trying to allow a user to upload multiple files at once in Flask – which will then be saved and processed. Currently, it is working with with a single file upload. I tried to implement a solution based on other things I have read online, such as here but it still only processes one file. The below is said attempt at a solution:

@app.route('/', methods=['POST', 'GET'])
def file_upload():
    if request.method == "POST":
        print("method is post")
        if request.files:
            for file_to_upload in request.files.getlist("uploaded_file"):  
                file_to_upload.seek(0, os.SEEK_END)
                file_length = file_to_upload.tell()
                filename = secure_filename(file_to_upload.filename)
                if file_to_upload.filename == "": # Checks the file name isn't blank
                    print("File name must not be blank")
                    return redirect(request.url)
                elif not allowed_ext(file_to_upload.filename): # Checks the file has an allowed extension
                    print("File extension not supported")
                    return redirect(request.url)
                elif file_length > app.config['MAX_FILE_SIZE']: # Checks file size
                    print("File too big")
                    return redirect(request.url)
                else: # Else, passes all validation and is saved.
                    file_to_upload.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                    return render_template('index.html', succ="Your file(s) are now being processed.")
        else: # If no files request, redirect to index.
            return redirect(request.url)
    else: # If not a POST request, load page as normal.
        return render_template('index.html', is_home='yes')

def allowed_ext(filename):
    if not "." in filename:
        return False

    ext = filename.rsplit(".", 1)[1]

    if ext.upper() in app.config["ALLOWED_EXTENSIONS"]:
        return True
        return False

def check_file_name(filename):
<!-- Allows the user to upload their files for processing -->
<div class="tile is-vertical is-parent coach" id='fileUploadTile'>
    <div class="tile is-child box has-background-light">
        <div class="columns">
            <div class="column is-one-third"></div>
            <div class="column is-one-third">
                <div id='fileUploader' class="file has-name is-boxed is-centered">
                  <form action='/' method='POST' enctype="multipart/form-data">
                  <label class="file-label">
                      <input class="file-input"  type="file" multiple name="uploaded_file" id='fileLoader'>
                      <span class="file-cta">
                        <span class="file-icon">
                          <i class="fas fa-upload"></i>
                        <span class="file-label">
                          Select file(s) to parse!
                      <span class="file-name">
                  <div>Or simply drag and drop!</div>
            {% if success_msg is defined %}
            {% endif %}
            <div class="column is-one-third"></div>
          <div class='buttons are-medium' id='fileButtons'> 
            <input type='submit' class="button is-success is-light" value='Process file(s)'> 
          <button class='button is-danger is-light' name='resetFiles' id='resetFiles'>Reset Files</button>
  </div> <!-- end of column-->


Any and all help would be much appreciated 🙂


The problem with your attempt has nothing to do with Flask – it is a "Python" problem.

You iterate over all uploaded files, but you break the for-loop with the return statement (return render_template(...).

So, you have to iterate over all files, and then, only outside the for-loop return.

Simple example

for fruit in ['apple', 'bananas']:
    return  # too early!!
for fruit in ['apple', 'bananas']:
return  # <- right time to return

Answered By – Jürgen Gmach

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published