前端部分(增改功能包含文件上传)
基础页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>主页</title>
<style>
table {
border: 1px solid black;
border-collapse: collapse;
width: 800px;
}
th,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<table>
<caption>
<h2>学员管理</h2><a href="./edit.html">新增</a>
</caption>
<thead>
<tr>
<th>头像</th>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>电话</th>
<th>专业</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
页面渲染与删除功能
import $ from 'jquery'
function list() {
$('tbody').empty();
$.get('/api/student/list').then(res => {
// console.log(res);
let arr = res;
arr.forEach(item => {
let tr = $(`<tr>
<td><img src='http://localhost:8082${item.photo}'width='50px'/></td>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.sex}</td>
<td>${item.age}</td>
<td>${item.tel}</td>
<td>${item.major}</td>
<td>
<button class='modifyBtn' stuId='${item.id}'>修改</button>
<button class="delBtn" stuId='${item.id}'>删除</button>
</td>
</tr>`)
tr.appendTo('tbody')
});
})
}
$(document).on('click', '.modifyBtn', function () {
let id = $(this).attr('stuId');
location.href = 'edit.html?id=' + id;
})
$(document).on('click', '.delBtn', function () {
if (window.confirm('确定删除吗?')) {
let id = $(this).attr('stuId');
$.ajax({
type: 'DELETE',
url: '/api/student/del?id=' + id
}).then(res => {
console.log(res);
list();
})
}
})
list()
增加修改页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>新增学员</title>
<style>
.addstudent {
border: 1px solid black;
width: 300px;
position: relative;
left: 300px;
/* top: -100px; */
background-color: white;
text-indent: 2em;
opacity: 0.9;
}
input {
position: relative;
left: 20px;
height: 25px;
}
span {
position: relative;
left: 20px;
}
#photo {
width: 150px;
height: 150px;
border: 1px dashed gray;
text-align: center;
line-height: 150px;
font-size: 50px;
}
img {
width: 150px;
}
</style>
</head>
<body>
<div class="addstudent">
<div class="iconfont icon-guanbi" id="close"></div>
<h1>新增学员信息</h1>
<div id="photo">十</div>
<!-- 文件域通过hidden进行隐藏 -->
<input type="file" id="myfile" hidden>
<span>姓名</span>
<br>
<input type="text" placeholder=" 请输入学员姓名" id="name">
<br>
<span>性别</span>
<br>
<input type="radio" name="sex" checked value="男"> 男
<input type="radio" name="sex" value="女"> 女
<br>
<span>年龄</span>
<br>
<input type="text" placeholder=" 请输入学员年龄" id="age">
<br>
<span>专业</span>
<br>
<input type="text" placeholder=" web" id="major">
<br>
<span>
电话
</span>
<br>
<input type="text" placeholder=" 请输入学员电话" id="tel">
<br>
<br>
<button id="btn">提交</button>
</div>
</body>
</html>
增改功能实现
import $ from 'jquery'
let id = location.search.split('=')[1]
if (id) {
$.get('/api/student/detail', { id }).then(res => {
let stu = res;
$('#name').val(stu.name);
$('#age').val(stu.age);
$('#major').val(stu.major);
$('#tel').val(stu.tel);
$(`input[value=${stu.sex}]`).prop('checked', true);
let photo = 'http://localhost:8082' + stu.photo;
$('#photo').html(`<img src='${photo}'/>`)
})
}
//点击+,打开文件选择对话框
$("#photo").on('click', function () {
//触发文件域的单击事件
$("#myfile").trigger("click");
})
$('#myfile').on('change', function () {
//通过文件读取器获取图片
let file = this.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (res) {
//预览图片
let img = new Image();
img.src = res.target.result;
$("#photo").html(img);//innerHTML
}
})
$('#btn').on('click', function () {
let name = $('#name').val();
let age = $('#age').val();
let sex = $('input[name=sex]:checked').val();
let tel = $("#tel").val();
let major = $('#major').val();
let photo = document.getElementById("myfile").files[0]
let formData = new FormData();
formData.append('photo', photo)
formData.append('name', name)
formData.append('age', age)
formData.append('sex', sex)
formData.append('major', major)
formData.append('tel', tel)
if (id) {
formData.append('id', id)
$.ajax({
type: "PUT",
url: "/api/student/modify",
processData: false,
contentType: false,
data: formData,
}).then(res => {
location.href = 'index.html',
console.log(res);
})
} else {
$.ajax({
type: 'post',
url: '/api/student/add',
processData: false,
contentType: false,
data: formData,
success(res) {
console.log('新增数据结果:', res);
location.href = 'index.html'
}
})
}
})
后端部分
const path = require('path')
const fs = require('fs');
var express = require('express');
const router = express.Router();
const DB = require('../utils/Db')
//../utils/Db 存放虚拟数据(类数据库)
//列表
router.get('/list', function (req, res) {
res.send(DB.students)
})
function createName(file) {
var time = Date.now();
var random = parseInt(Math.random() * 1000);
var extname = path.extname(file.originalname);
var filename = time + random + extname;
return filename;
}
//增加
router.post('/add', function (req, res) {
req.body['id'] = Date.now();
if (req.files && req.files.length > 0) {
//说明这次有文件要上传
let file = req.files[0];
//生成文件名
let filename = createName(file);
//将文件名添加到该学员信息中
req.body['photo'] = "/images/" + filename;
//上传
upload(req, res, "新增成功", filename);
} else {
//说明这次没有文件上传
res.send({ msg: "添加成功", status: 200 })
}
DB.students.push(req.body);
})
//修改
router.put('/modify', function (req, res) {
//获取要修改的学号(id),去匹配对应的学员,返回学员下标
let index = DB.students.findIndex(item => {
return item.id == req.body.id;
})
//用新值将原来该学员的信息全部覆盖一遍
DB.students[index] = {
id: req.body.id,
name: req.body.name,
tel: req.body.tel,
age: req.body.age,
major: req.body.major,
sex: req.body.sex,
//默认直接取该学员原始的photo
photo: DB.students[index].photo
}
if (req.files && req.files.length > 0) {
//说明这次有文件要上传
let file = req.files[0];
let filename = createName(file);
//替换photo
DB.students[index].photo = "/images/" + filename;
upload(req, res, "修改", filename);
} else {
res.send({ msg: "修改成功", status: 200 })
}
})
//上传文件
function upload(req, res, title, filename) {
for (let i = 0; i < req.files.length; i++) {
let file = req.files[i];
fs.readFile(file.path, function (err, data) {
if (err) {
console.log("文件读取失败:", err);
}
fs.writeFile(path.resolve(__dirname, '..', 'public', 'images', filename), data, function (err) {
if (err) {
console.log("文件写入失败:", err);
//失败
res.end({ msg: title + "失败", status: 201 });
return;
}
//成功
res.send({ msg: title + "成功", status: 200 });
})
})
}
}
//删除
router.delete('/del', function (req, res) {
let index = DB.students.findIndex(item => {
return item.id == req.query.id;
})
if (index == -1) {
res.send({
msg: "该学员不存在",
status: 201
})
} else {
DB.students.splice(index, 1);
res.send({
msg: '删除成功',
status: 200
})
}
})
//查询
router.get('/detail', function (req, res) {
let id =req.query.id;
let stu = DB.students.find(item => item.id == id);
res.send(stu);
})
module.exports = router;