首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Flask文件上传

Python Flask文件上传
EN

Stack Overflow用户
提问于 2020-05-26 13:23:24
回答 2查看 91关注 0票数 0

这是我用python flask写的上传excel文件的代码:

代码语言:javascript
复制
    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:

代码语言:javascript
复制
<form action="process" method="post" enctype="multipart/form-data" >
<input type="file" name="xlfile"  id="">
<button type="submit" class="btn btn-primary">Submit</button>

但是,当我上传文件并单击submit时,我得到了这个错误:

代码语言:javascript
复制
    werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
    KeyError: 'xlfile

请帮我解决这个问题。

代码语言:javascript
复制
note
/*
I did the coding as in [https://www.youtube.com/watch?v=tJKHrLzcopo] video
*/
EN

回答 2

Stack Overflow用户

发布于 2020-05-26 14:45:49

它应该是

代码语言:javascript
复制
f = request.files['xlfile']

而不是

代码语言:javascript
复制
f=request.form["xlfile"]

并且,用action='/process'替换action="process"

票数 0
EN

Stack Overflow用户

发布于 2020-05-26 17:11:46

这应该会对你有所帮助:

代码语言:javascript
复制
@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>"

也可以查看这个post

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62015175

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档