chore: 支持上传图片及sass语法

This commit is contained in:
2025-11-13 14:55:45 +08:00
parent d8275a2781
commit 6f842ef328
5 changed files with 1113 additions and 5 deletions

View File

@@ -3,6 +3,7 @@ import cors from 'cors';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import multer from 'multer';
// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
@@ -12,12 +13,47 @@ const app = express();
const PORT = 3000;
const CONFIG_FILE_PATH = path.join(__dirname, 'data', 'config.json');
// 创建上传目录
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
// 配置multer
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadDir);
},
filename: (req, file, cb) => {
const timestamp = Date.now();
const ext = path.extname(file.originalname);
const filename = `${timestamp}${ext}`;
cb(null, filename);
}
});
const upload = multer({
storage,
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB限制
fileFilter: (req, file, cb) => {
const allowedTypes = /jpeg|jpg|png|gif/;
const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = allowedTypes.test(file.mimetype);
if (extname && mimetype) {
return cb(null, true);
} else {
cb(new Error('只允许上传图片文件JPEG、JPG、PNG、GIF'));
}
}
});
// 中间件
app.use(cors());
app.use(express.json());
// 静态文件服务Vue应用
// 静态文件服务Vue应用和上传的图片
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/uploads', express.static(uploadDir));
// API: 获取配置数据
app.get('/api/config', (req, res) => {
@@ -41,6 +77,44 @@ app.post('/api/config', (req, res) => {
}
});
// API: 上传图片
app.post('/api/upload', upload.single('image'), (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: '没有文件上传' });
}
// 返回文件的相对路径
const relativePath = `/uploads/${req.file.filename}`;
res.json({
success: true,
filePath: relativePath,
filename: req.file.filename
});
} catch (error) {
console.error('文件上传失败:', error);
res.status(500).json({ error: error.message || '文件上传失败' });
}
});
// API: 删除图片
app.delete('/api/upload/:filename', (req, res) => {
try {
const filename = req.params.filename;
const filePath = path.join(uploadDir, filename);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
res.json({ success: true });
} else {
res.status(404).json({ error: '文件不存在' });
}
} catch (error) {
console.error('文件删除失败:', error);
res.status(500).json({ error: '文件删除失败' });
}
});
// 处理Vue Router历史模式 - 使用正则表达式代替通配符
app.get(/^((?!\/api).)*$/, (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));