import { readMultipartFormData, createError } from 'h3' import { writeFileSync, mkdirSync } from 'node:fs' import { dirname, join } from 'node:path' import { randomBytes } from 'node:crypto' import { requireAdmin } from '../../utils/auth' import { getConfig } from '../../utils/config' import { writeAudit } from '../../utils/audit' const MAX_SIZE = 8 * 1024 * 1024 // 8MB const EXT_BY_TYPE: Record = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif', 'image/webp': 'webp', 'image/svg+xml': 'svg', 'image/avif': 'avif', } /** * 后台图片上传 -> 保存到 PVC 的 uploads 目录(/data/uploads), * 通过 /uploads/ 对外提供。 */ export default defineEventHandler(async (event) => { requireAdmin(event) const parts = await readMultipartFormData(event) const file = parts?.find((p) => p.name === 'file' && p.data?.length) if (!file || !file.data) { throw createError({ statusCode: 400, message: '缺少文件', data: { code: 'VALIDATION_ERROR' } }) } const type = file.type || 'application/octet-stream' const ext = EXT_BY_TYPE[type] if (!ext) { throw createError({ statusCode: 400, message: '仅支持图片(png/jpg/gif/webp/svg/avif)', data: { code: 'VALIDATION_ERROR' } }) } if (file.data.length > MAX_SIZE) { throw createError({ statusCode: 400, message: '文件过大(上限 8MB)', data: { code: 'VALIDATION_ERROR' } }) } const name = `${Date.now()}-${randomBytes(6).toString('hex')}.${ext}` const dir = join(dirname(getConfig().dbPath), 'uploads') mkdirSync(dir, { recursive: true }) writeFileSync(join(dir, name), file.data) writeAudit(event, 'upload', `upload:${name}`) return { ok: true, url: `/uploads/${name}` } })