import { createError } from 'h3' import { readFileSync, existsSync } from 'node:fs' import { join, dirname, normalize } from 'node:path' import { getConfig } from '../../utils/config' const MIME: Record = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', avif: 'image/avif', } /** * 服务上传的图片(存于 PVC uploads 目录) */ export default defineEventHandler((event) => { const path = getRouterParam(event, 'path') ?? '' const base = normalize(join(dirname(getConfig().dbPath), 'uploads')) const filePath = normalize(join(base, path)) // 防目录穿越 if (!filePath.startsWith(base + '/') && filePath !== base) { throw createError({ statusCode: 403, message: 'Forbidden' }) } if (!existsSync(filePath)) { throw createError({ statusCode: 404, message: 'Not Found' }) } const ext = filePath.split('.').pop()?.toLowerCase() ?? '' const data = readFileSync(filePath) return new Response(new Uint8Array(data), { headers: { 'Content-Type': MIME[ext] || 'application/octet-stream', 'Cache-Control': 'public, max-age=31536000, immutable', }, }) })