const Router = require('koa-router') const multer = require('@koa/multer') const path = require('path') const fs = require('fs') const router = new Router() const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'] const MAX_SIZE = 5 * 1024 * 1024 const uploadDir = path.join(__dirname, '..', 'public', 'uploads') const storage = multer.diskStorage({ destination: (req, file, cb) => { const type = (req.query && req.query.type) || 'goods' const dir = path.join(uploadDir, type) if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }) } cb(null, dir) }, filename: (req, file, cb) => { const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9) const ext = path.extname(file.originalname) cb(null, uniqueSuffix + ext) } }) const upload = multer({ storage, limits: { fileSize: MAX_SIZE }, fileFilter: (req, file, cb) => { if (ALLOWED_TYPES.includes(file.mimetype)) { cb(null, true) } else { cb(new Error('不支持的文件类型,仅支持 jpg/png/gif/webp')) } } }) router.post('/', upload.single('file'), async (ctx) => { if (!ctx.file) { ctx.status = 400 ctx.body = { code: 400, message: '没有上传文件' } return } const type = ctx.query.type || 'goods' const fileUrl = `/uploads/${type}/${ctx.file.filename}` ctx.body = { code: 200, message: '上传成功', url: fileUrl } }) module.exports = router.routes()