一、准备开发环境与核心工具
定制版轻量档案管理系统无需复杂框架,以下工具组合完全满足基础需求,可直接复制命令安装。
1.1 开发环境(Windows/Mac通用)
1.2 验证环境安装
打开终端(Windows用PowerShell/CMD,Mac用终端),依次执行以下命令,返回对应版本号即成功:
```bash
验证Node.js
node -v
验证npm(Node.js自带包管理)
npm -v
验证MySQL(需先配置环境变量,安装时勾选"Add to PATH"默认配置)
mysql -V
```
二、创建后端服务(Express + MySQL2)
2.1 初始化后端项目
在桌面创建文件夹 custom-archive,右键用VS Code打开,终端执行:
```bash
创建后端子文件夹
mkdir backend
cd backend
初始化npm项目(一路回车即可)
npm init -y
安装依赖
npm install express mysql2 cors multer
```
2.2 配置MySQL数据库
终端登录MySQL(需输入安装时设置的root密码):
```bash
mysql -u root -p
```
登录后依次执行以下SQL语句,创建数据库、表和专用用户:
```sql
-- 创建数据库
CREATE DATABASE archive_db DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 切换到数据库
USE archive_db;
-- 创建档案表
CREATE TABLE archives (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL COMMENT '档案标题',
type VARCHAR(50) NOT NULL COMMENT '档案类型',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
file_path VARCHAR(500) COMMENT '文件存储路径',
file_size BIGINT COMMENT '文件大小(字节)'
) COMMENT='档案主表';
-- 创建专用用户(用户名archive_user,密码Archive123!)
CREATE USER 'archive_user'@'localhost' IDENTIFIED BY 'Archive123!';
-- 授权
GRANT ALL PRIVILEGES ON archive_db. TO 'archive_user'@'localhost';
-- 刷新权限
FLUSH PRIVILEGES;
-- 退出MySQL
EXIT;
```
2.3 编写后端代码

在backend文件夹下创建三个文件:
(1)配置文件 db.config.js
```javascript
module.exports = {
host: "localhost",
user: "archive_user",
password: "Archive123!",
database: "archive_db",
port: 3306
};
```
(2)后端主程序 server.js
```javascript
const express = require("express");
const cors = require("cors");
const multer = require("multer");
const mysql = require("mysql2/promise");
const dbConfig = require("./db.config");
const path = require("path");
const fs = require("fs");
const app = express();
const PORT = 3001;
// 启用CORS跨域
app.use(cors());
// 解析JSON请求体
app.use(express.json());
// 创建静态文件存储目录
const uploadDir = path.join(__dirname, "uploads");
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir);
// 配置文件上传(multer)
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, uploadDir),
filename: (req, file, cb) => {
const uniqueName = `${Date.now()}-${file.originalname}`;
cb(null, uniqueName);
}
});
const upload = multer({ storage: storage });
// 初始化数据库连接池
let pool;
async function initDB() {
pool = mysql.createPool(dbConfig);
try {
await pool.getConnection();
console.log("MySQL连接成功");
} catch (err) {
console.error("MySQL连接失败:", err);
process.exit(1);
}
}
initDB();
// 接口1:获取所有档案
app.get("/api/archives", async (req, res) => {
const [rows] = await pool.query("SELECT FROM archives ORDER BY update_time DESC");
res.json(rows);
});
// 接口2:新增档案(含文件上传)
app.post("/api/archives", upload.single("file"), async (req, res) => {
const { title, type } = req.body;
const file = req.file;
const insertData = [
title,
type,
file ? `/uploads/${file.filename}` : null,
file ? file.size : null
];
await pool.query(
"INSERT INTO archives (title, type, file_path, file_size) VALUES (?, ?, ?, ?)",
insertData
);
res.json({ success: true });
});
// 接口3:删除档案(含本地文件删除)
app.delete("/api/archives/:id", async (req, res) => {
const [archive] = await pool.query("SELECT FROM archives WHERE id = ?", [req.params.id]);
if (archive[0]?.file_path) {
const localPath = path.join(__dirname, archive[0].file_path);
if (fs.existsSync(localPath)) fs.unlinkSync(localPath);
}
await pool.query("DELETE FROM archives WHERE id = ?", [req.params.id]);
res.json({ success: true });
});
// 暴露静态文件
app.use("/uploads", express.static(uploadDir));
// 启动服务
app.listen(PORT, () => console.log(`后端服务运行在 http://localhost:${PORT}`));
```
(3)启动脚本 package.json修改
打开backend/package.json,找到"scripts"字段,替换为:
```json
"scripts": {
"start": "node server.js"
},
```
三、创建前端界面(原生HTML/CSS/JS)
3.1 初始化前端项目
在custom-archive文件夹下创建子文件夹 frontend,在其中创建index.html、style.css、script.js三个文件。
3.2 编写前端代码
(1)index.html
```html
定制版档案管理系统
```
(2)style.css
```css
{ margin: 0; padding: 0; box-sizing: border-box; font-family: Arial, sans-serif; }
.container { max-width: 1200px; margin: 20px auto; padding: 0 20px; }
h1 { text-align: center; color: 333; margin-bottom: 30px; }
form { border: 1px solid eee; padding: 20px; border-radius: 8px; margin-bottom: 30px; }
.form-group { margin-bottom: 15px; }
.form-group label { display: inline-block; width: 100px; font-weight: bold; }
.form-group input, .form-group select { width: calc(100% - 110px); padding: 8px; border: 1px solid ddd; border-radius: 4px; }
button { padding: 8px 20px; background-color: 409eff; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background-color: 66b1ff; }
h2 { color: 333; margin-bottom: 15px; }
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid eee; padding: 10px; text-align: left; }
th { background-color: f5f5f5; }
.delete-btn { background-color: f56c6c; }
.delete-btn:hover { background-color: f78989; }
```
(3)script.js
```javascript
const API_BASE = "http://localhost:3001/api";
const addForm = document.getElementById("addForm");
const archiveList = document.getElementById("archiveList");
// 页面加载时获取档案列表
window.onload = async () => await loadArchives();
// 加载档案列表
async function loadArchives() {
const res = await fetch(`${API_BASE}/archives`);
const archives = await res.json();
archiveList.innerHTML = archives.map(archive => `
| ${archive.id} |
${archive.title} |
${archive.type} |
${archive.create_time.replace("T", " ").substring(0, 19)} |
${archive.file_path ? `下载` : "无"} |
|
`).join("");
}
// 新增档案
addForm.onsubmit = async (e) => {
e.preventDefault();
const formData = new FormData(addForm);
await fetch(`${API_BASE}/archives`, { method: "POST", body: formData });
addForm.reset();
await loadArchives();
};
// 删除档案
async function deleteArchive(id) {
if (!confirm("确定要删除该档案吗?")) return;
await fetch(`${API_BASE}/archives/${id}`, { method: "DELETE" });
await loadArchives();
}
```
四、启动并测试系统
4.1 启动后端服务
在VS Code的backend终端(若未打开,右键backend文件夹选“在集成终端中打开”)执行:
```bash
npm start
```
看到“MySQL连接成功”“后端服务运行在 http://localhost:3001”即成功。
4.2 启动前端界面
右键frontend/index.html,选择“在默认浏览器中打开”(VS Code需安装Live Server插件,右键选“Open with Live Server”更稳定,插件下载地址 VS Code插件市场)。
4.3 核心功能测试
- 新增无文件档案:填写标题、类型,点击“新增档案”,列表出现对应记录
- 新增带文件档案:选择本地文件后重复上述操作,列表出现“下载”按钮
- 下载文件:点击“下载”按钮,浏览器下载对应文件
- 删除档案:点击“删除”按钮,确认后列表和本地uploads文件夹的文件同步删除