'passing a filename as a parameter from a for loop in python flask

I am uploading file so i am trying to pass a filename after looping through but i am getting an unbountLocalerror. i have tried making the filename global so that it can be seen outside the for loop but its throwing filename not defined. what other way can i use to get the filename so i can use it in html/jinja

@app.route('/upload', methods=['POST'])
def upload():

    target = os.path.join(APP_ROOT,'static/')
    if not os.path.isdir(target):
        os.mkdir(target)
    else:
        for upload in request.files.getlist('file'):
            filename = upload.filename
            destination = "/".join([target, filename])
            upload.save(destination)
    return render_template("upload.html",filename=filename)


Solution 1:[1]

  • The error occurred because you created the local variable inside the else statement.
  • If, for example the condition was that it triggered the if: part of the code, the local variable filename would never be created.
  • Therefore, the unbound error occurred when you tried to access it in return render_template("upload.html",filename=filename).
  • It also seems that you wanted to return multiple renders - because you don't have just one filename but bunch of them.
  • I changed the function to return the list of render_template objects created based on filenames list that is being appended on line 10 ( filenames.append(upload.filename)).

Code:

@app.route('/upload', methods=['POST'])
def upload():

    target = os.path.join(APP_ROOT,'static/')
    if not os.path.isdir(target): #Create the target folder if it doesnt exitst
        os.mkdir(target)

    filenames = []
    for upload in request.files.getlist('file'): #Upload files into the folder
        filenames.append(upload.filename)
        destination = "/".join([target, upload.filename])
        upload.save(destination)

    return [render_template("upload.html",filename = filename) for filename in filenames] #Return therender_template

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Patrick Yoder