- POST /api/admin/uploads (multipart, ≤8MB, ตรวจ magic bytes JPEG/PNG/WebP/AVIF) เก็บ data/uploads/cinemas/ คืน /uploads/cinemas/<slug>-<random>-<ts>.<ext> - GET /uploads/** เสิร์ฟไฟล์อัปโหลด (Nitro route, immutable cache, กัน path traversal) - PhotosEditor: ปุ่มอัปโหลด + ลากไฟล์มาวาง + Ctrl+V วางจากคลิปบอร์ด, หลายไฟล์พร้อมกัน - app/lib/upload.ts กติกากลาง + upload.spec.ts (13 tests) - docs: api.md, admin-guide.md (วิธีอัปโหลด), DESIGN.md, README
45 lines
1.7 KiB
TypeScript
45 lines
1.7 KiB
TypeScript
/**
|
|
* GET /uploads/** — เสิร์ฟรูปที่อัปโหลดจากหลังบ้าน (เก็บที่ data/uploads/)
|
|
*
|
|
* ใช้ Nitro route เพราะโฟลเดอร์ public/ ถูก copy ตอน build
|
|
* → ไฟล์ที่เขียนตอน runtime ต้องเสิร์ฟเอง
|
|
*/
|
|
import { promises as fs } from "node:fs";
|
|
import path from "node:path";
|
|
|
|
import { createError, defineEventHandler, getRouterParam, setResponseHeaders } from "h3";
|
|
|
|
import { safeUploadPath, typeForExtension } from "../../../app/lib/upload";
|
|
|
|
const UPLOAD_ROOT = path.join(process.cwd(), "data", "uploads");
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const raw = getRouterParam(event, "path") ?? "";
|
|
const relative = safeUploadPath(decodeURIComponent(raw));
|
|
if (!relative) {
|
|
throw createError({ statusCode: 400, statusMessage: "พาธไฟล์ไม่ถูกต้อง" });
|
|
}
|
|
|
|
const filePath = path.join(UPLOAD_ROOT, relative);
|
|
const resolved = path.resolve(filePath);
|
|
if (!resolved.startsWith(path.resolve(UPLOAD_ROOT))) {
|
|
throw createError({ statusCode: 403, statusMessage: "ไม่อนุญาต" });
|
|
}
|
|
|
|
let data: Buffer;
|
|
try {
|
|
data = await fs.readFile(resolved);
|
|
} catch {
|
|
throw createError({ statusCode: 404, statusMessage: "ไม่พบไฟล์" });
|
|
}
|
|
|
|
const ext = path.extname(resolved).replace(".", "").toLowerCase();
|
|
setResponseHeaders(event, {
|
|
"Content-Type": typeForExtension(ext),
|
|
"Content-Length": String(data.byteLength),
|
|
// ชื่อไฟล์มี timestamp+random → cache ได้ยาว
|
|
"Cache-Control": "public, max-age=31536000, immutable",
|
|
});
|
|
return data;
|
|
});
|