开发CSV文件上传分析页面:HTML前端与Flask后端实现需求
完整实现CSV文件上传与后端分析功能
Flask后端完善代码(app.py)
from flask import Flask, request, jsonify import os app = Flask(__name__) # 创建上传文件保存目录(不存在则自动生成) UPLOAD_FOLDER = 'uploads' os.makedirs(UPLOAD_FOLDER, exist_ok=True) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route('/mainFunc1', methods=['POST']) def main_func1(): # 校验文件是否存在 if 'file1' not in request.files: return jsonify({'error': '未上传CSV文件'}), 400 file = request.files['file1'] # 校验是否选择了文件 if file.filename == '': return jsonify({'error': '未选择CSV文件'}), 400 # 校验文件格式为CSV if file and file.filename.endswith('.csv'): # 保存文件到指定目录 file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename) file.save(file_path) # 读取表单参数 query需求 = request.form.get('inp') 文本列 = request.form.get('file2') 主题列 = request.form.get('file3') # 此处添加后续分析逻辑,比如读取CSV文件进行数据处理 # 示例:打印获取到的参数信息 print(f"查询需求: {query需求}") print(f"文本列: {文本列}") print(f"主题列: {主题列}") print(f"上传文件路径: {file_path}") return jsonify({'message': '文件上传成功,已开始分析', 'file_path': file_path}), 200 else: return jsonify({'error': '仅支持上传CSV格式文件'}), 400 if __name__ == '__main__': app.run(debug=True)
HTML页面完善代码(mainFunc.html)
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>CSV文件分析工具</title> <style> .form-container { max-width: 600px; margin: 2rem auto; padding: 2rem; border: 1px solid #ddd; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .form-group { margin-bottom: 1.5rem; } label { display: block; margin-bottom: 0.5rem; font-weight: bold; } input[type="file"], input[type="text"] { width: 100%; padding: 0.8rem; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; } button { background-color: #007bff; color: white; padding: 0.8rem 1.5rem; border: none; border-radius: 4px; cursor: pointer; font-size: 1rem; } button:hover { background-color: #0056b3; } </style> </head> <body> <div class="form-container"> <h2>CSV文件分析上传</h2> <form action="/mainFunc1" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="file1">上传CSV文件:</label> <input type="file" id="file1" name="file1" accept=".csv" required> </div> <div class="form-group"> <label for="inp">查询需求:</label> <input type="text" id="inp" name="inp" placeholder="请输入你的查询需求" required> </div> <div class="form-group"> <label for="file2">文本列名称:</label> <input type="text" id="file2" name="file2" placeholder="请输入CSV中文本列的列名" required> </div> <div class="form-group"> <label for="file3">主题列名称:</label> <input type="text" id="file3" name="file3" placeholder="请输入CSV中主题列的列名" required> </div> <button type="submit">提交分析</button> </form> </div> </body> </html>
功能说明
- 后端部分:
- 自动创建上传目录,避免文件保存失败
- 增加多层校验逻辑,确保上传的文件符合要求
- 成功接收文件和参数后,预留了后续分析的代码入口
- 返回JSON格式响应,方便前端处理结果
- 前端部分:
- 添加基础样式优化页面体验
- 为每个输入项添加清晰的标签和提示文字
- 设置必填校验和文件格式限制,减少无效提交
内容的提问来源于stack exchange,提问作者Данил Димитров
相关产品推荐
相关产品推荐

