Python Flask Загрузка файла - PullRequest
0 голосов
/ 26 мая 2020

Это код, который я написал в python flask для загрузки файла Excel:

    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>

Но когда я загружаю файл и нажимаю «Отправить», я получаю следующую ошибку:

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

Пожалуйста, помогите мне решить проблему.

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

Ответы [ 2 ]

0 голосов
/ 26 мая 2020

Это должно вам помочь:

@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>"

См. Также этот пост :

0 голосов
/ 26 мая 2020

Это должно быть

f = request.files['xlfile']

вместо

f=request.form["xlfile"]

И замените action="process" на action='/process'.

...