Ai config
This commit is contained in:
+24
-15
@@ -5,16 +5,19 @@ const fs = require('fs')
|
||||
|
||||
const router = new Router()
|
||||
|
||||
// 确保上传目录存在
|
||||
const uploadDir = path.join(__dirname, '..', 'public', 'uploads')
|
||||
if (!fs.existsSync(uploadDir)) {
|
||||
fs.mkdirSync(uploadDir, { recursive: true })
|
||||
}
|
||||
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
|
||||
const MAX_SIZE = 5 * 1024 * 1024
|
||||
|
||||
const uploadDir = path.join(__dirname, '..', 'public', 'uploads')
|
||||
|
||||
// 配置 multer
|
||||
const storage = multer.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
cb(null, uploadDir)
|
||||
const type = 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)
|
||||
@@ -23,21 +26,27 @@ const storage = multer.diskStorage({
|
||||
}
|
||||
})
|
||||
|
||||
const upload = multer({ storage })
|
||||
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: '没有上传文件'
|
||||
}
|
||||
ctx.body = { code: 400, message: '没有上传文件' }
|
||||
return
|
||||
}
|
||||
|
||||
// 存储相对路径,前端使用时拼接域名
|
||||
const fileUrl = `/uploads/${ctx.file.filename}`
|
||||
const type = ctx.query.type || 'goods'
|
||||
const fileUrl = `/uploads/${type}/${ctx.file.filename}`
|
||||
ctx.body = {
|
||||
code: 200,
|
||||
message: '上传成功',
|
||||
|
||||
Reference in New Issue
Block a user