0

This is the code I have written in python flask to upload a excel file :

    from flask import Flask,render_template,request
    import csv  

    app=Flask(__name__,template_folder="/Users/viru/Downloads/Login_v5")

    @app.route("/",methods=['GET','POST'])
    def upload():
        return render_template("fileform.html")

    @app.route("/process",methods=['GET','POST'])
    def batchPass():
        if request.method == "POST":
            l=[]
            f=request.form["xlfile"]
            with open(f) as file:
                csvfile=csv.reader(file)
                for row in csvfile:
                    l.append(row)
                return f"<h1>{{l}}</h1>"


    if __name__ == "__main__":
        app.run(debug=True)

fileform.html:

<form action="process" method="post" enctype="multipart/form-data" >
<input type="file" name="xlfile"  id="">
<button type="submit" class="btn btn-primary">Submit</button>

But when I upload the file and click submit I get this error :

    werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
    KeyError: 'xlfile

Please help me solve the issue.

note
/*
I did the coding as in [https://www.youtube.com/watch?v=tJKHrLzcopo] video
*/
viruchith
  • 51
  • 1
  • 8

2 Answers2

0

It should be

f = request.files['xlfile']

instead of

f=request.form["xlfile"]

And, replace action="process" with action='/process'.

ngShravil.py
  • 4,742
  • 3
  • 18
  • 30
0

This should help you:

@app.route("/process",methods=['GET','POST'])
def batchPass():
    if request.method == "POST":
        l=[]
        f=request.files["xlfile"]
        # Use custom logic to save file safely.
        f.save(f.filename)
        with open(f.filename) as file:
            csvfile=csv.reader(file)
            for row in csvfile:
                l.append(row)
        os.unlink(f.filename)
        return f"<h1>{l}</h1>"

See this post as well:

Balaji Ambresh
  • 4,977
  • 2
  • 5
  • 17