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

Flask图片上传展示功能报错:Method Not Allowed问题排查

Flask图片上传展示问题修复方案

问题根源分析

  • Method Not Allowed错误:前端表单以POST方法提交到/view_report,但后端该路由仅配置了GET方法,不接受POST请求。
  • 配置项错误:app.config[" UPLOAD_FOLDER"]存在多余空格,导致无法正确读取上传目录配置。
  • 路由跳转错误:上传成功后使用url_for('upload_img1.html')是错误用法,url_for应传入视图函数名而非模板文件名。
  • 图片路径生成错误:view_img函数中用url_for(path)生成静态文件路径的方式错误,且直接redirect无法展示页面,应渲染模板并传递图片路径。
  • 模板变量缺失:前端模板未正确接收后端传递的图片文件名,导致无法渲染图片。

修正后的Python后端代码

import os
from flask import Flask, flash, request, render_template, redirect, url_for, session
from werkzeug.utils import secure_filename
from datetime import timedelta

Upload_path = r'static\images'
allowed_ext = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)

app.secret_key = "helloWorld"
app.permanent_session_lifetime = timedelta(minutes=5)
# 移除配置项中的多余空格
app.config["UPLOAD_FOLDER"] = Upload_path

# 新增文件扩展名验证函数
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_ext

@app.route("/", methods=['GET','POST'])
def upload_file():
    if request.method == "POST":
        session.permanent = True
        if "file" not in request.files:
            flash('没有选择文件')
            return redirect(request.url)
        file = request.files['file']

        if file.filename == '':
            flash("未选择文件")
            return redirect(request.url)
        
        # 验证文件扩展名
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            session['filename'] = filename 
            # 跳转到view_img对应的路由
            return redirect(url_for('view_img'))
        else:
            flash("不允许的文件类型")
            return redirect(request.url)
    return render_template('upload_img1.html')
        
@app.route("/view_report")
def view_img():
    if "filename" in session:
        filename = session['filename']
        # 渲染展示模板并传递文件名
        return render_template('view_report.html', filename=filename)
    return "未上传文件"

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

修正后的前端模板

上传页面(upload_img1.html)

<!DOCTYPE html>
<html>
    <head>
        <title>上传报告</title>
    </head>
    <body>
        <h1>上传报告</h1>
        <!-- 表单提交到根路由,对应upload_file处理逻辑 -->
        <form action="/" method="POST" enctype='multipart/form-data'>
            <p><input type='file' name='file'></p>
            <p><input type='submit' value='上传'></p>
        </form> 
        <!-- 显示上传提示信息 -->
        {% with messages = get_flashed_messages() %}
            {% if messages %}
                {% for msg in messages %}
                    <p>{{ msg }}</p>
                {% endfor %}
            {% endif %}
        {% endwith %}
    </body>
</html>

展示页面(view_report.html)

<!DOCTYPE html>
<html>
    <head>
        <title>查看报告</title>
    </head>
    <body>
        <h1>上传的图片</h1>
        {% if filename %}
        <div>
            <!-- 正确生成静态图片的访问URL -->
            <img src="{{ url_for('static', filename='images/' + filename) }}" alt="上传的图片">
        </div>
        {% else %}
        <p>没有上传的图片</p>
        {% endif %}
        <p><a href="{{ url_for('upload_file') }}">返回上传页面</a></p>
    </body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:10:03