parent
c5d5dcee3a
commit
dc009ef2a4
@ -0,0 +1,80 @@
|
||||
const express = require('express');
|
||||
const multer = require('multer');
|
||||
const XLSX = require('xlsx');
|
||||
const mysql = require('mysql2');
|
||||
const cors = require('cors');
|
||||
|
||||
const app = express();
|
||||
const port = 3001;
|
||||
|
||||
// 使用 CORS
|
||||
app.use(cors());
|
||||
|
||||
// 设置 multer 存储配置
|
||||
const storage = multer.memoryStorage();
|
||||
const upload = multer({
|
||||
storage: storage,
|
||||
limits: { fileSize: 5 * 1024 * 1024 } // 5MB 限制
|
||||
});
|
||||
|
||||
// 创建数据库连接池
|
||||
const pool = mysql.createPool({
|
||||
host: 'localhost',
|
||||
user: 'root',
|
||||
password: 'mysql123',
|
||||
database: 'mysql'
|
||||
});
|
||||
|
||||
// 处理文件上传的路由
|
||||
app.post('/upload', upload.single('file'), (req, res) => {
|
||||
try {
|
||||
const file = req.file;
|
||||
if (!file) {
|
||||
return res.status(400).json({ message: 'No file uploaded.' });
|
||||
}
|
||||
|
||||
// 使用 xlsx 库读取 Excel 文件
|
||||
const workbook = XLSX.read(file.buffer, { type: 'buffer' });
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const worksheet = workbook.Sheets[sheetName];
|
||||
const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
|
||||
|
||||
// 插入数据到数据库
|
||||
data.forEach(row => {
|
||||
const query = 'INSERT INTO students (student_id, name, points) VALUES (?, ?, ?)';
|
||||
pool.query(query, [row.student_id, row.name, row.points], (error, results, fields) => {
|
||||
if (error) {
|
||||
console.error('Error inserting data:', error);
|
||||
} else {
|
||||
console.log('Row inserted successfully:', row);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
res.json({ message: 'File uploaded and processed successfully!' });
|
||||
} catch (error) {
|
||||
console.error('Error processing file:', error);
|
||||
res.status(500).json({ message: 'Error processing file: ' + error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 新的API端点来返回随机学生数据
|
||||
app.get('/api/get-random-student', (req, res) => {
|
||||
// 注意:这里需要实现从数据库中获取随机学生数据的逻辑
|
||||
// 由于这需要数据库操作,这里只是一个示例
|
||||
pool.query('SELECT * FROM students ORDER BY RAND() LIMIT 1', (error, results) => {
|
||||
if (error) {
|
||||
console.error('Error fetching random student:', error);
|
||||
return res.status(500).json({ message: 'Error fetching random student' });
|
||||
}
|
||||
if (results.length === 0) {
|
||||
return res.status(404).json({ error: 'No students found.' });
|
||||
}
|
||||
const randomStudent = results[0];
|
||||
res.json(randomStudent);
|
||||
});
|
||||
});
|
||||
|
||||
app.listen(port, () => {
|
||||
console.log(`Server is running on http://localhost:${port}`);
|
||||
});
|
Loading…
Reference in new issue