更新完善页面
This commit is contained in:
+19
-8
@@ -2,17 +2,23 @@ const Router = require('koa-router')
|
||||
const multer = require('@koa/multer')
|
||||
const path = require('path')
|
||||
const fs = require('fs')
|
||||
const { requireStaffAuth } = require('../middleware/auth')
|
||||
|
||||
const router = new Router()
|
||||
|
||||
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
|
||||
const ALLOWED_EXTS = ['.jpg', '.jpeg', '.png', '.gif', '.webp']
|
||||
const MAX_SIZE = 5 * 1024 * 1024
|
||||
const ALLOWED_BUCKETS = ['goods', 'points', 'avatar', 'category']
|
||||
|
||||
const uploadDir = path.join(__dirname, '..', 'public', 'uploads')
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
const type = (req.query && req.query.type) || 'goods'
|
||||
if (!ALLOWED_BUCKETS.includes(type)) {
|
||||
return cb(new Error('非法的上传目录'))
|
||||
}
|
||||
const dir = path.join(uploadDir, type)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
@@ -21,24 +27,24 @@ const storage = multer.diskStorage({
|
||||
},
|
||||
filename: (req, file, cb) => {
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9)
|
||||
const ext = path.extname(file.originalname)
|
||||
cb(null, uniqueSuffix + ext)
|
||||
const ext = (path.extname(file.originalname) || '').toLowerCase()
|
||||
const safeExt = ALLOWED_EXTS.includes(ext) ? ext : '.jpg'
|
||||
cb(null, uniqueSuffix + safeExt)
|
||||
}
|
||||
})
|
||||
|
||||
const upload = multer({
|
||||
storage,
|
||||
limits: { fileSize: MAX_SIZE },
|
||||
limits: { fileSize: MAX_SIZE, files: 1 },
|
||||
fileFilter: (req, file, cb) => {
|
||||
if (ALLOWED_TYPES.includes(file.mimetype)) {
|
||||
cb(null, true)
|
||||
} else {
|
||||
cb(new Error('不支持的文件类型,仅支持 jpg/png/gif/webp'))
|
||||
if (!ALLOWED_TYPES.includes(file.mimetype)) {
|
||||
return cb(new Error('不支持的文件类型,仅支持 jpg/png/gif/webp'))
|
||||
}
|
||||
cb(null, true)
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/', upload.single('file'), async (ctx) => {
|
||||
router.post('/', requireStaffAuth(), upload.single('file'), async (ctx) => {
|
||||
if (!ctx.file) {
|
||||
ctx.status = 400
|
||||
ctx.body = { code: 400, message: '没有上传文件' }
|
||||
@@ -46,6 +52,11 @@ router.post('/', upload.single('file'), async (ctx) => {
|
||||
}
|
||||
|
||||
const type = ctx.query.type || 'goods'
|
||||
if (!ALLOWED_BUCKETS.includes(type)) {
|
||||
ctx.status = 400
|
||||
ctx.body = { code: 400, message: '非法的上传目录' }
|
||||
return
|
||||
}
|
||||
const fileUrl = `/uploads/${type}/${ctx.file.filename}`
|
||||
ctx.body = {
|
||||
code: 200,
|
||||
|
||||
Reference in New Issue
Block a user