Compare commits

..

3 Commits

Author SHA1 Message Date
wangsiyuan 172bbc1be3 更新 views.py 2023-12-28 19:17:03 +08:00
wangsiyuan 1ebdfa44c8 创建 allowed_files.py 2023-12-28 19:17:01 +08:00
wangsiyuan bb2104539c 更新 import-class.html 2023-12-28 19:16:58 +08:00
3 changed files with 90 additions and 5 deletions

View File

@ -68,8 +68,11 @@
</fieldset>
</div>
<div class="layui-col-md12" style="padding-top: 20px;">
<!-- 隐藏的文件输入,用户选择文件 -->
<input type="file" id="excelFile" style="display:none;" accept=".xlsx, .xls">
<!-- 上传按钮 -->
<button type="button" class="layui-btn" id="uploadExcel">上传Excel文件</button>
<!-- 可以添加一个下载模板的链接 -->
<!-- 下载模板链接 -->
<a href="/files/template.xlsx" class="layui-btn layui-btn-primary">下载模板</a>
</div>
</div>
@ -82,6 +85,52 @@
<script src="/static/js/menu.js"></script>
<script src="/static/js/logout.js"></script>
<script>
// 获取上传按钮和文件输入元素
var uploadBtn = document.getElementById('uploadExcel');
var fileInput = document.getElementById('excelFile');
// 当点击上传按钮时触发文件输入的点击事件
uploadBtn.addEventListener('click', function () {
fileInput.click();
});
// 处理文件选择事件
fileInput.addEventListener('change', function () {
var file = this.files[0]; // 获取文件对象
if (file) {
// 检查文件类型
var fileName = file.name;
var fileExt = fileName.split('.').pop().toLowerCase();
if (fileExt === 'xlsx' || fileExt === 'xls') {
// 使用 FormData 上传文件
var formData = new FormData();
formData.append('file', file, fileName); // 'file' 是你的服务器端期待的字段名
// 使用 fetch 发送文件
fetch('/api/receive-excel', {
method: 'POST',
body: formData // 传递表单数据
})
.then(response => {
if (response.ok) {
return response.json(); // 如果上传成功解析JSON响应
}
throw new Error('Network response was not ok.'); // 如果上传失败,抛出错误
})
.then(data => {
// 处理响应数据
layer.msg('上传成功!'); // 弹出成功消息
})
.catch(error => {
console.error('Upload failed:', error);
alert("文件上传失败!"); // 弹出失败消息
});
} else {
alert("请上传Excel文件!");
}
}
});
</script>
</body>
</html>

View File

@ -0,0 +1,2 @@
def allowed_excel(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'xlsx', 'xls'}

View File

@ -1,4 +1,9 @@
import os
import openpyxl as openpyxl
from flask import Flask, redirect, url_for, render_template, session, jsonify, request, send_file
from utils.allowed_files import allowed_excel
from db.connection import MySQLPool
from config import SECRET_KEY
from db.database_manager import DatabaseManager
@ -8,6 +13,7 @@ from models.User import User
import logging
from config import LOGGING_CONFIG
from config import FILE_PATH
app = Flask(__name__, static_folder='static')
app.secret_key = SECRET_KEY # 从配置文件设置
logging.basicConfig(**LOGGING_CONFIG)
@ -17,6 +23,7 @@ mysql_pool = MySQLPool()
# 配置文件路径,例如指向一个 'files' 目录
app.config['FILE_PATH'] = FILE_PATH
@app.route('/')
def index():
# 如果用户已登录,则重定向到主页;否则,重定向到登录页面
@ -250,12 +257,39 @@ def get_current_teacher_courses():
# 将查询结果转换为JSON格式并返回
return jsonify(response)
@app.route('/files/<filename>')
@app.route('/files/template.xlsx')
def download_template():
print(FILE_PATH)
# 确保这个路径是你的文件实际所在的服务器路径
path = "./files/template.xlsx"
path = os.path.join(app.config['FILE_PATH'], "template.xlsx")
return send_file(path, as_attachment=True)
@app.route('/api/receive-excel', methods=['POST'])
def receive_excel():
# 检查是否有文件在请求中
if 'file' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['file']
# 如果用户没有选择文件,浏览器也会提交一个空的文件名
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
# 检查文件是不是 Excel 文件
if file and allowed_excel(file.filename):
try:
# 使用 openpyxl 读取文件内容
workbook = openpyxl.load_workbook(file)
# TODO: 在这里处理你的Excel文件例如读取数据
print(workbook)
return jsonify({"message": "File successfully processed"}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
else:
return jsonify({"error": "Invalid file type"}), 400
if __name__ == '__main__':
app.run(debug=True)