首页 > 解决方案 > Python - 烧瓶和 werkzeug - 继续给出“BadRequestKeyError:400 Bad Request:KeyError:'file'”

问题描述

我第一次尝试用python上传文件,我尝试使用flask和werkzeug库,这是我的代码:

在这里,我正在创建上传文件的功能:

@app.route('/upload')
def upload_file():
    return render_template('load.html')

@app.route('/uploader', methods=['GET','POST'])
@login_required(must=[be_admin, have_approval])
def uploaderV():
    if request.method == 'POST':
       file = request.files['file']
       if file:
          filename = secure_filename(file.filename)
          file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
          return 'file uploaded'
    return render_template('load.html')

这是我的 load.html 页面:

{% extends 'base.html' %}
{% block title %}Secret{% endblock %}
{% block page_body %}
     <div class="row">
          <form action="{{ url_for('uploaderV') }}" method="POST" enctype="multipart/form-data">
               <p>
                   <input type='file' name='file[]' multiple=''>
                   <input type="submit" value="Upload">
               </p>
          </form>
     </div>
{% endblock %}

每次我尝试上传文件时,服务器都会给我
werkzeug.exceptions.BadRequestKeyError BadRequestKeyError: 400 Bad Request: KeyError: 'file'
我尝试了不同的方式,现在我真的不知道该怎么做。

标签: pythonflaskhttp-status-code-400werkzeug

解决方案


你输入的名字是file[],不是file。尝试类似:

   file = request.files['file[]']

或者只是将您的输入名称更改为file.


推荐阅读