const Router = require('koa-router');
const multer = require('@koa/multer');
const pool = require('../database/index'); // 确保路径正确
const verifyLogin = require('../middleware/verify-login'); // 如果需要身份验证
const uploadRouter = new Router({ prefix: '/upload' });
// 设置 multer 存储配置
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // 文件保存路径,你需要确保这个目录存在
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, uniqueSuffix + '-' + file.originalname);
}
});
const upload = multer({ storage });
// 文件上传路由
uploadRouter.post('/file', verifyLogin, upload.single('file'), async (ctx) => {
const { bookLendingId } = ctx.request.body;
const file = ctx.file;
if (!file) {
ctx.status = 400;
ctx.body = { code: 400, message: '文件上传失败' };
return;
}
try {
// 保存文件信息到 borrow_files 表
const sql = 'INSERT INTO borrow_files (borrow_id, original_name, path) VALUES (?, ?, ?)';
await pool.query(sql, [bookLendingId, file.originalname, file.path]);
ctx.status = 200;
ctx.body = { code: 200, message: '文件上传成功', filePath: file.path };
} catch (err) {
ctx.status = 500;
ctx.body = { code: 500, message: '服务器错误', error: err.message };
}
});
module.exports = uploadRouter;