Python Flask文件上传

问题描述 投票:0回答:1

这是我用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
*/
python python-3.x web flask file-handling
1个回答
0
投票

应该是

f = request.files['xlfile']

而不是

f=request.form["xlfile"]

并且,更换 action="process"action='/process'.


0
投票

这应该对你有帮助。

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

看这个 岗位 也是。

© www.soinside.com 2019 - 2024. All rights reserved.