npm install express multer moment
main.js
const express = require('express');
const multer = require('multer');
const moment = require('moment');
const fs = require('fs');
const app = express();
// 设置中间件和路由
app.use(express.json()); // 解析JSON数据
app.use(express.urlencoded({ extended: true })); // 解析URL编码数据
// 使用multer中间件处理文件上传
const upload = multer({ dest: 'uploads/' });
// 创建路由以处理POST请求
app.post('/upload', upload.single('file'), (req, res) => {
// 获取上传的文件
const file = req.file;
// 获取文件的扩展名
const ext = file.originalname.split('.').pop();
// 生成新的文件名,格式为年月日_时分秒.txt
const newName = moment().format('YYYYMMDD_HHmmss') + '.' + ext;
// 将文件从临时目录移动到当前目录,并重命名文件
fs.rename(file.path, `./${newName}`, (err) => {
if (err) {
console.error(err);
return res.status(500).send();
}
console.log(`File ${file.originalname} has been uploaded and saved as ${newName}`);
res.send(`File ${file.originalname} has been uploaded and saved as ${newName}`);
});
});
// 启动服务器并监听端口3000
app.listen(3000, () => {
console.log('Server started on port 3000');
});
编写一个 start.bat 文件.
@echo off
cd /d "%~dp0"
node app.js
pause
# node main.js 请替换成你创建的文件目录即可,后续使用时双击打开即可。