36 lines
1.1 KiB
JavaScript
36 lines
1.1 KiB
JavaScript
import { Router } from 'express';
|
|
import multer, { diskStorage } from 'multer';
|
|
import { join, extname } from 'path';
|
|
import { existsSync, mkdirSync } from 'fs';
|
|
|
|
const router = Router();
|
|
|
|
// 设置存储引擎
|
|
const storage = diskStorage({
|
|
destination: function (req, file, cb) {
|
|
const tempDir = join(__dirname, '../../static/Temp');
|
|
if (!existsSync(tempDir)){
|
|
mkdirSync(tempDir, { recursive: true }); // 添加 recursive 参数以确保目录递归创建
|
|
}
|
|
cb(null, tempDir);
|
|
},
|
|
filename: function (req, file, cb) {
|
|
cb(null, Date.now() + extname(file.originalname)); // 重命名文件以避免冲突
|
|
}
|
|
});
|
|
|
|
const upload = multer({ storage: storage });
|
|
|
|
// 添加API路由来处理文件上传
|
|
router.post('/uploadImage', upload.single('file'), (req, res) => {
|
|
if (!req.file) {
|
|
return res.status(400).send('No file uploaded.');
|
|
}
|
|
// 返回图片保存的地址与文件名
|
|
const fileResponse = {
|
|
filePath: req.file.path,
|
|
fileName: req.file.filename
|
|
};
|
|
res.json(fileResponse);
|
|
});
|
|
export default router; |