【m】消息接收发送
This commit is contained in:
@@ -9,6 +9,7 @@ import { reset as resetHandler }from './class/httphandler';
|
||||
import { initSwagger } from './swagger';
|
||||
|
||||
const cors = require('cors');
|
||||
const multer = require('multer');
|
||||
|
||||
export const createServer = (config: Options): express.Express => {
|
||||
const app: express.Express = express();
|
||||
@@ -39,5 +40,50 @@ export const createServer = (config: Options): express.Express => {
|
||||
// 初始化Swagger
|
||||
initSwagger(app, config);
|
||||
|
||||
// 配置multer存储
|
||||
const storage = multer.diskStorage({
|
||||
destination: function (req: any, file: any, cb: (error: Error | null, destination: string) => void) {
|
||||
// 确保上传目录存在
|
||||
const uploadDir = path.join(__dirname, '../client/public/uploads/avatars');
|
||||
if (!fs.existsSync(uploadDir)) {
|
||||
fs.mkdirSync(uploadDir, { recursive: true });
|
||||
}
|
||||
cb(null, uploadDir);
|
||||
},
|
||||
filename: function (req: any, file: any, cb: (error: Error | null, filename: string) => void) {
|
||||
// 临时使用原始文件名,稍后在API处理中重命名
|
||||
cb(null, file.originalname);
|
||||
}
|
||||
});
|
||||
|
||||
const upload = multer({ storage: storage });
|
||||
|
||||
// 头像上传API
|
||||
app.post('/api/upload/avatar', upload.single('avatar'), (req: any, res: express.Response) => {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ success: false, message: 'No file uploaded' });
|
||||
}
|
||||
|
||||
const userId = req.body.userId || 'unknown';
|
||||
const ext = path.extname(req.file.originalname);
|
||||
const oldPath = req.file.path;
|
||||
const newFilename = `${userId}${ext}`;
|
||||
const newPath = path.join(path.dirname(oldPath), newFilename);
|
||||
|
||||
// 重命名文件
|
||||
fs.rename(oldPath, newPath, (err) => {
|
||||
if (err) {
|
||||
console.error('Error renaming file:', err);
|
||||
return res.status(500).json({ success: false, message: '文件重命名失败' });
|
||||
}
|
||||
|
||||
const avatarUrl = `/uploads/avatars/${newFilename}`;
|
||||
res.json({ success: true, avatarUrl: avatarUrl });
|
||||
});
|
||||
});
|
||||
|
||||
// 确保uploads目录可访问
|
||||
app.use('/uploads', express.static(path.join(__dirname, '../client/public/uploads')));
|
||||
|
||||
return app;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user