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

如何上传文件并在网页指定区域动态展示其内容?

我来帮你搞定这个问题!核心问题在于你之前用的GET请求没法传递文件,得换成POST请求并使用FormData来处理文件上传,同时后端也要对应调整接收逻辑。下面是完整的解决方案:

核心修改思路

  1. 前端:替换$.getJSON为$.ajax(因为GET无法携带文件),用FormData封装上传的文件,同时配置必要的参数确保文件能正确传输。
  2. 后端:在接口中接收上传的文件,直接在内存中用Pandas读取处理,再返回符合DataTables要求的JSON格式数据。
  3. 增加错误处理:对无文件上传、非CSV文件、处理异常等情况给出友好提示。

修改后的完整代码

后端 app.py

from flask import Flask, render_template, request, jsonify
import pandas as pd
import json

# Initialize the Flask application
app = Flask(__name__)

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

@app.route('/_get_table', methods=["POST"])  # 仅保留POST方法,适配文件上传
def get_table():
    # 获取上传的文件
    file = request.files.get('myfile')
    if not file or file.filename == '':
        return jsonify(error="请先选择一个文件!")
    
    # 简单校验文件格式
    if not file.filename.endswith('.csv'):
        return jsonify(error="请上传CSV格式的文件!")
    
    try:
        # 直接读取内存中的文件,无需保存到本地
        df = pd.read_csv(file)
        # 转换为DataTables需要的JSON结构
        df_json = df.to_json(orient="split")
        df_data = json.loads(df_json)
        return jsonify(
            my_table=df_data["data"],
            columns=[{"title": str(col)} for col in df_data["columns"]]
        )
    except Exception as e:
        return jsonify(error=f"文件处理出错:{str(e)}")

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

前端 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="header">
            <h3 class="text-center text-muted">Some great stuff</h3>
        </div>
        <hr class="mb-4">
        <div class="custom-file">
            <!-- 添加accept限制仅选择CSV文件,提升用户体验 -->
            <input id="myfile" name="myfile" type="file" class="custom-file-input" accept=".csv">
            <label for="myfile" class="custom-file-label"> Choose file... </label>
        </div><br><br>
        <button class="btn btn-primary" type="button" id="upload_document">Upload and process!</button>
        <hr class="mb-4">
        <table id="pretty_table" class="table table-striped"></table>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                var table = null;

                $('#upload_document').bind('click', function() {
                    // 获取选中的文件
                    const fileInput = $('#myfile')[0];
                    const file = fileInput.files[0];
                    if (!file) {
                        alert("请先选择一个文件!");
                        return;
                    }

                    // 创建FormData对象封装文件
                    const formData = new FormData();
                    formData.append('myfile', file);

                    // 发送POST请求处理文件
                    $.ajax({
                        url: '/_get_table',
                        type: 'POST',
                        data: formData,
                        processData: false,  // 禁止jQuery自动处理数据,避免破坏文件格式
                        contentType: false,  // 禁止jQuery设置Content-Type,由FormData自动生成正确的头部
                        success: function(data) {
                            if (data.error) {
                                alert(data.error);
                                return;
                            }
                            // 销毁旧表格并渲染新表格
                            if (table !== null) {
                                table.destroy();
                                table = null;
                                $("#pretty_table").empty();
                            }
                            table = $("#pretty_table").DataTable({
                                data: data.my_table,
                                columns: data.columns
                            });
                        },
                        error: function() {
                            alert("文件上传失败,请重试!");
                        }
                    });

                    return false;
                });

                $('.custom-file-input').on('change', function() {
                    let fileName = $(this).val().split('\\').pop();
                    $(this).next('.custom-file-label').addClass("selected").html(fileName);
                });
            });
        </script>
    </div>
</body>
</html>

关键细节说明

  • 前端FormData:这是浏览器原生的对象,专门用于传输二进制数据(比如文件),配合processData: false和contentType: false可以确保文件正确上传到后端。
  • 后端文件处理:直接读取request.files中的文件对象,Pandas的read_csv支持直接读取文件流,无需将文件保存到本地,高效又节省磁盘空间。
  • 错误处理:覆盖了无文件、格式错误、处理异常等场景,给用户明确的提示信息,提升交互体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:08:19