You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask文件上传触发werkzeug.exceptions.BadRequestKeyError问题求助

解决Flask文件上传时BadRequestKeyError的问题

在实现文件上传功能时,表单已设置name="imagefile",但后端仍抛出werkzeug.exceptions.BadRequestKeyError: 400 Bad Request错误,无法检测到imagefile字段。以下是我使用的Flask后端代码和前端HTML代码,求修复方案:

后端代码

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/',methods=['GET'])


@app.route('/', methods=["POST"])
def predict():
    imagefile = request.files['imagefile']
    image_path = "./images/"+imagefile.filename
    imagefile.save(image_path)

    return render_template('index.html')

if __name__ == '__main__':
    app.run(port=3000, debug=True)

前端HTML代码

<!DOCTYPE html>
<html>
    <head>
        <title>Tutorial</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    </head>

    <body>
        <h1>Image Classifer</h1>

        <form class="p-3 text-center" action='/', method="post" enctype="multipart/form-data"> 
            <input class="form-control" type="file" name='imagefile' >
            <input class="btn btn-primary mt-3" type="submit" value="Predict Image" >
        </form>
    </body>
</html>

问题根源及修复方案

  1. 合并冗余路由
    你定义了两个重复的根路由,其中第一个@app.route('/',methods=['GET'])未绑定视图函数,会导致路由逻辑混乱。将GET和POST方法合并到同一个路由中:
@app.route('/', methods=['GET', 'POST'])
def predict():
    # 后续逻辑
  1. 安全获取上传文件
    当用户未选择文件就提交时,直接通过request.files['imagefile']取值会触发BadRequestKeyError。改用get方法安全获取,并检查文件是否有效:
def predict():
    if request.method == 'POST':
        imagefile = request.files.get('imagefile')
        # 确保有文件且文件名不为空
        if imagefile and imagefile.filename != '':
            # 执行保存逻辑
  1. 确保保存目录存在
    如果./images/目录不存在,调用imagefile.save()会抛出文件不存在错误。提前创建目录:
import os

app = Flask(__name__)
# 不存在则自动创建目录,避免报错
os.makedirs('./images', exist_ok=True)

完整修复后的后端代码

from flask import Flask, render_template, request
import os

app = Flask(__name__)
os.makedirs('./images', exist_ok=True)

@app.route('/', methods=['GET', 'POST'])
def predict():
    if request.method == 'POST':
        imagefile = request.files.get('imagefile')
        if imagefile and imagefile.filename:
            # 使用os.path.join避免路径拼接问题
            image_path = os.path.join('./images', imagefile.filename)
            imagefile.save(image_path)
        return render_template('index.html')
    # GET请求直接返回页面
    return render_template('index.html')

if __name__ == '__main__':
    app.run(port=3000, debug=True)

内容的提问来源于stack exchange,提问作者NavoNator3000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 14:37:27