import { createError } from 'h3' import { readFileSync, existsSync } from 'node:fs' import { join, dirname, normalize } from 'node:path' import { getConfig } from '../../utils/config' import { getOssConfig, getObject } from '../../utils/s3' 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', } const mimeFromName = (name: string) => MIME[name.split('.').pop()?.toLowerCase() ?? ''] || 'application/octet-stream' /** * 服务上传的图片: * - OSS 已配置 -> 从桶 arcticnewone 拉取(key 为 /uploads/ 的 path) * - OSS 无该对象或未配置 -> 回退读取本地 /data/uploads(兼容历史已上传内容) */ export default defineEventHandler(async (event) => { const path = getRouterParam(event, 'path') ?? '' const oss = getOssConfig() if (oss) { try { const res = await getObject(path) if (res) { return new Response(res.body, { headers: { 'Content-Type': res.headers.get('content-type') || mimeFromName(path), 'Cache-Control': 'public, max-age=31536000, immutable', }, }) } } catch (err) { console.error('[uploads] oss read failed, fallback to local:', err) } } // 本地回退 const base = normalize(join(dirname(getConfig().dbPath), 'uploads')) const filePath = normalize(join(base, path.split('/').join('/'))) if (!filePath.startsWith(base + '/')) { throw createError({ statusCode: 403, message: 'Forbidden' }) } if (!existsSync(filePath)) { throw createError({ statusCode: 404, message: 'Not Found' }) } const data = readFileSync(filePath) return new Response(new Uint8Array(data), { headers: { 'Content-Type': mimeFromName(filePath), 'Cache-Control': 'public, max-age=31536000, immutable', }, }) })