|
|
|
|
const express = require('express');
|
|
|
|
|
const multer = require('multer');
|
|
|
|
|
const path = require('path');
|
|
|
|
|
const fs = require('fs');
|
|
|
|
|
const fsPromises = fs.promises;
|
|
|
|
|
const morgan = require('morgan');
|
|
|
|
|
|
|
|
|
|
// 创建 Express 应用实例
|
|
|
|
|
const app = express();
|
|
|
|
|
const PORT = 3000; // 可以根据需要修改端口
|
|
|
|
|
|
|
|
|
|
// 设置文件存储配置
|
|
|
|
|
const storage = multer.diskStorage({
|
|
|
|
|
destination: async (req, file, cb) => {
|
|
|
|
|
const uploadDir = 'uploads/';
|
|
|
|
|
try {
|
|
|
|
|
// 检查 uploads 目录是否存在,如果不存在,则创建它
|
|
|
|
|
await fsPromises.mkdir(uploadDir, { recursive: true });
|
|
|
|
|
cb(null, uploadDir); // 指定文件上传目录
|
|
|
|
|
} catch (error) {
|
|
|
|
|
cb(error);
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
filename: (req, file, cb) => {
|
|
|
|
|
cb(null, Date.now() + path.extname(file.originalname));
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// 创建上传实例,设置文件大小和类型限制
|
|
|
|
|
const upload = multer({
|
|
|
|
|
storage,
|
|
|
|
|
limits: { fileSize: 5 * 1024 * 1024 }, // 限制文件大小为5MB
|
|
|
|
|
fileFilter: (req, file, cb) => {
|
|
|
|
|
const filetypes = /jpeg|jpg|png|gif|pdf/; // 允许的文件类型
|
|
|
|
|
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
|
|
|
|
|
const mimetype = filetypes.test(file.mimetype);
|
|
|
|
|
|
|
|
|
|
if (mimetype && extname) {
|
|
|
|
|
return cb(null, true);
|
|
|
|
|
}
|
|
|
|
|
cb(new Error('只允许上传 JPEG, PNG, GIF 和 PDF 文件'));
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// 中间件用于解析 JSON 和 URL 编码的数据
|
|
|
|
|
app.use(express.json());
|
|
|
|
|
app.use(express.urlencoded({ extended: true }));
|
|
|
|
|
app.use(morgan('combined')); // 记录请求日志
|
|
|
|
|
|
|
|
|
|
// 设置静态文件服务以提供前端页面
|
|
|
|
|
app.use(express.static(path.join(__dirname, 'public')));
|
|
|
|
|
|
|
|
|
|
// 定义文件上传接口
|
|
|
|
|
app.post('/api/upload', upload.single('file'), (req, res) => {
|
|
|
|
|
if (!req.file) {
|
|
|
|
|
return res.status(400).json({ message: '没有文件上传' });
|
|
|
|
|
}
|
|
|
|
|
res.status(200).json({ message: '文件上传成功', filename: req.file.filename });
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// 错误处理
|
|
|
|
|
app.use((err, req, res, next) => {
|
|
|
|
|
if (err instanceof multer.MulterError) {
|
|
|
|
|
return res.status(400).json({ message: err.message });
|
|
|
|
|
} else if (err) {
|
|
|
|
|
console.error(err.stack);
|
|
|
|
|
return res.status(500).json({ message: '服务器内部错误' });
|
|
|
|
|
}
|
|
|
|
|
next();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// 启动服务器
|
|
|
|
|
app.listen(PORT, () => {
|
|
|
|
|
console.log(`Server is running on http://localhost:${PORT}`);
|
|
|
|
|
});
|