You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
81 lines
2.3 KiB
81 lines
2.3 KiB
1 month ago
|
const express = require('express');
|
||
|
const multer = require('multer');
|
||
|
const cors = require('cors');
|
||
|
const fs = require('fs');
|
||
|
const path = require('path');
|
||
|
const morgan = require('morgan');
|
||
|
|
||
|
const app = express();
|
||
|
const port = 3000;
|
||
|
|
||
|
// Middleware
|
||
|
app.use(cors({
|
||
|
origin: 'http://your-frontend-domain.com', // 指定允许的源
|
||
|
methods: ['GET', 'POST'],
|
||
|
}));
|
||
|
app.use(express.json());
|
||
|
app.use(express.static(path.join(__dirname, 'public'))); // 提供静态文件
|
||
|
app.use(morgan('combined')); // 记录请求日志
|
||
|
|
||
|
// 创建上传目录
|
||
|
const uploadsDir = path.join(__dirname, 'uploads');
|
||
|
if (!fs.existsSync(uploadsDir)) {
|
||
|
fs.mkdirSync(uploadsDir, { recursive: true });
|
||
|
}
|
||
|
|
||
|
// Multer setup for file uploads
|
||
|
const storage = multer.diskStorage({
|
||
|
destination: (req, file, cb) => {
|
||
|
cb(null, uploadsDir); // 确保上传目录存在
|
||
|
},
|
||
|
filename: (req, file, cb) => {
|
||
|
cb(null, Date.now() + path.extname(file.originalname)); // Append timestamp to avoid name collisions
|
||
|
}
|
||
|
});
|
||
|
|
||
|
const upload = multer({
|
||
|
storage,
|
||
|
limits: {
|
||
|
fileSize: 5 * 1024 * 1024 // 限制文件大小为5MB
|
||
|
},
|
||
|
fileFilter: (req, file, cb) => {
|
||
|
const filetypes = /csv|txt|json/; // 允许的文件类型
|
||
|
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('Error: File type not supported!'));
|
||
|
}
|
||
|
});
|
||
|
|
||
|
// Endpoint to handle file import
|
||
|
app.post('/import', upload.single('file'), (req, res) => {
|
||
|
if (!req.file) {
|
||
|
return res.status(400).send('No file uploaded.');
|
||
|
}
|
||
|
console.log(req.file);
|
||
|
res.send('File imported successfully!');
|
||
|
});
|
||
|
|
||
|
// Endpoint to handle file export
|
||
|
app.get('/export', (req, res) => {
|
||
|
const filePath = path.join(__dirname, 'exports', 'sample-data.csv'); // 确保该文件存在
|
||
|
res.download(filePath, 'sample-data.csv', (err) => {
|
||
|
if (err) {
|
||
|
console.error(err);
|
||
|
res.status(500).send('Error exporting file.');
|
||
|
}
|
||
|
});
|
||
|
});
|
||
|
|
||
|
// 路由
|
||
|
app.get('/api/hello', (req, res) => {
|
||
|
res.send('Hello, world!');
|
||
|
});
|
||
|
|
||
|
// 启动服务器
|
||
|
app.listen(port, () => {
|
||
|
console.log(`Server running at http://localhost:${port}`);
|
||
|
});
|