0

I'm working on an upload file function for my web tool and I'm facing an issue. The problem is that Flask is not receiving the files from the HTML form. I have already set the route, and created the form tag accordingly to what is required like the method POST and still not working. Am I doing anything wrong?

HTML

<form action="/" method="POST" enctype="multipart/form-data" class="form-horizontal">
   <div class="row form-group">
      <div class="col-12 col-md-12">
         <div class="control-group" id="fields">
            <label class="control-label" for="field1">
               Requests
            </label>
            <div class="controls">
               <div class="entry input-group upload-input-group">
                  <input class="form-control" name="fields[]" type="file">
                  <button class="btn btn-upload btn-success btn-add" type="button">
                     <i class="fa fa-plus"></i>
                  </button>
               </div>
            </div>
            <button class="btn btn-primary" type="submit" value="Submit">Upload</button>
         </div>
      </div>
   </div>
</form>

Python/Flask

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

app=Flask(__name__)

app.secret_key = "secret key"
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

path = os.getcwd()
# file Upload
UPLOAD_FOLDER = os.path.join(path, 'uploads')

if not os.path.isdir(UPLOAD_FOLDER):
    os.mkdir(UPLOAD_FOLDER)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


ALLOWED_EXTENSIONS = set(['xlsx', 'xls'])


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


@app.route('/')
def upload_form():
    return render_template('index.html')


@app.route('/', methods=['POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No file selected for uploading')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            flash('File successfully uploaded')
            return redirect('/')
        else:
            flash('Allowed file types are xlsx and xls')
            return redirect(request.url)


if __name__ == "__main__":
    app.run(host = '127.0.0.1',port = 5000, debug = False)
Roberto
  • 91
  • 6

1 Answers1

1

Try changing the input name to file instead fields[]

<input class="form-control" name="file" type="file">