0x4A42
0x4A42

Reputation: 60

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
    else:
        return False

def check_file_name(filename):
    pass
<!-- 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>
        <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>
                        <span class="file-label">
                          Select file(s) to parse!
                        </span>
                      </span>
                      <span class="file-name">
                        
                      </span>
                    </label>
                  </div>
                  <div>Or simply drag and drop!</div>
            </div>
            {% if success_msg is defined %}
            {{success_msg}}
            {% endif %}
            <div class="column is-one-third"></div>
          </div>
          <div class='buttons are-medium' id='fileButtons'> 
            
          
              
            <input type='submit' class="button is-success is-light" value='Process file(s)'> 
          </form>
          <button class='button is-danger is-light' name='resetFiles' id='resetFiles'>Reset Files</button>
          </div>
    </div>
  </div> <!-- end of column-->

</div>

Any and all help would be much appreciated :)

Upvotes: 1

Views: 1258

Answers (1)

J&#252;rgen Gmach
J&#252;rgen Gmach

Reputation: 6093

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']:
    print(fruit)
    return  # too early!!
for fruit in ['apple', 'bananas']:
    print(fruit)
return  # <- right time to return

Upvotes: 2

Related Questions