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

Flask实现CSV无保存上传表格展示及404错误修复求助

Flask CSV上传展示404错误修复方案

问题根源分析

出现404错误的核心原因及潜在问题:

  • 重复初始化Flask应用:代码中先从FlaskWebProject2导入app,随后又重新创建app = Flask(__name__, ...),导致路由注册到了新的应用实例,而非实际运行的实例。
  • 目录结构缺失:未确认templateFiles、staticFiles、staticFiles/uploads目录是否存在,会引发模板加载失败或文件保存失败,间接导致404。
  • 表单路由不匹配:若首页表单的提交路径与/upload路由不一致,会触发404错误。

修复步骤及完整代码

1. 修正应用初始化问题

删除重复的from FlaskWebProject2 import app语句,确保所有路由注册到同一个Flask实例。

2. 确保目录存在

在项目根目录手动创建以下文件夹:

  • templateFiles:存放HTML模板文件
  • staticFiles/uploads:存放上传的CSV文件

3. 修复后的完整main.py代码

from datetime import datetime
from flask import Flask, render_template, request, session
import os
import pandas as pd
from werkzeug.utils import secure_filename

# Flask配置
UPLOAD_FOLDER = os.path.join('staticFiles', 'uploads')
ALLOWED_EXTENSIONS = {'csv'}

# 初始化Flask应用,指定模板和静态文件目录
app = Flask(__name__, template_folder='templateFiles', static_folder='staticFiles')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = 'This is your secret key to utilize session in Flask'

# 自动创建上传目录(避免手动创建)
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

def allowed_file(filename):
    # 验证文件是否为CSV格式
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods=['POST', 'GET'])
def uploadFile():
    if request.method == 'POST':
        # 获取上传文件
        uploaded_file = request.files.get('uploaded-file')
        if uploaded_file and allowed_file(uploaded_file.filename):
            data_filename = secure_filename(uploaded_file.filename)
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], data_filename)
            uploaded_file.save(file_path)
            # 存储文件路径到session
            session['uploaded_data_file_path'] = file_path
            return render_template('index_upload_and_show_data_page2.html')
        # 处理无效文件
        return render_template('index.html', error='请上传有效的CSV文件')
    # GET请求返回上传页面
    return render_template('index.html')

@app.route('/show_data')
def showData():
    data_file_path = session.get('uploaded_data_file_path', None)
    if not data_file_path or not os.path.exists(data_file_path):
        return render_template('index.html', error='未找到上传的文件')
    # 读取CSV并转换为带样式的HTML表格
    uploaded_df = pd.read_csv(data_file_path)
    uploaded_df_html = uploaded_df.to_html(classes='table table-striped', index=False)
    return render_template('show_csv_data.html', data_var=uploaded_df_html)

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

4. 配套模板文件示例

templateFiles/index.html

<!DOCTYPE html>
<html>
<head>
    <title>CSV上传工具</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h2>上传CSV文件</h2>
        {% if error %}
            <div class="alert alert-danger">{{ error }}</div>
        {% endif %}
        <form method="POST" action="/upload" enctype="multipart/form-data">
            <div class="mb-3">
                <label for="uploaded-file" class="form-label">选择CSV文件</label>
                <input class="form-control" type="file" id="uploaded-file" name="uploaded-file" accept=".csv" required>
            </div>
            <button type="submit" class="btn btn-primary">上传并查看数据</button>
        </form>
    </div>
</body>
</html>

templateFiles/index_upload_and_show_data_page2.html

<!DOCTYPE html>
<html>
<head>
    <title>上传成功</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h2>文件上传成功!</h2>
        <a href="/show_data" class="btn btn-success">查看数据表格</a>
        <a href="/" class="btn btn-secondary mt-2">返回上传页面</a>
    </div>
</body>
</html>

templateFiles/show_csv_data.html

<!DOCTYPE html>
<html>
<head>
    <title>CSV数据展示</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h2>CSV数据表格</h2>
        {{ data_var|safe }}
        <a href="/" class="btn btn-secondary mt-3">返回上传页面</a>
    </div>
</body>
</html>

运行验证

  1. 保存所有修改后,执行python main.py启动服务
  2. 访问http://localhost:5000,上传CSV文件
  3. 点击「查看数据表格」按钮,即可看到格式化后的表格数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 20:11:28