- 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
68 lines
2.3 KiB
TypeScript
68 lines
2.3 KiB
TypeScript
/**
|
|
* POST /api/admin/uploads — อัปโหลดรูปโรงหนังจากเครื่อง (multipart/form-data)
|
|
*
|
|
* ฟิลด์:
|
|
* file (บังคับ) — ไฟล์รูป jpeg/png/webp/avif ขนาด ≤ 8 MB
|
|
* slug (ไม่บังคับ) — ใช้ตั้งชื่อไฟล์ให้อ่านง่าย
|
|
*
|
|
* คืน: { url: "/uploads/cinemas/<ไฟล์>", bytes, type }
|
|
*/
|
|
import { promises as fs } from "node:fs";
|
|
import path from "node:path";
|
|
|
|
import { createError, defineEventHandler, readMultipartFormData } from "h3";
|
|
|
|
import { requireAdmin } from "@/lib/admin-auth.server";
|
|
import {
|
|
MAX_UPLOAD_BYTES,
|
|
UPLOAD_URL_PREFIX,
|
|
isValidImageUpload,
|
|
makeUploadName,
|
|
sniffImageType,
|
|
} from "@/lib/upload";
|
|
|
|
const UPLOAD_DIR = path.join(process.cwd(), "data", "uploads", "cinemas");
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
requireAdmin(event);
|
|
|
|
const parts = await readMultipartFormData(event);
|
|
const filePart = parts?.find((part) => part.name === "file" && part.data);
|
|
if (!filePart) {
|
|
throw createError({ statusCode: 400, statusMessage: "ไม่พบไฟล์ที่ส่งมา (field: file)" });
|
|
}
|
|
|
|
const bytes = new Uint8Array(filePart.data);
|
|
if (bytes.byteLength === 0) {
|
|
throw createError({ statusCode: 400, statusMessage: "ไฟล์ว่าง" });
|
|
}
|
|
if (bytes.byteLength > MAX_UPLOAD_BYTES) {
|
|
throw createError({
|
|
statusCode: 413,
|
|
statusMessage: `ไฟล์ใหญ่เกิน ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)} MB`,
|
|
});
|
|
}
|
|
|
|
// ไม่เชื่อ content-type จาก client — ตรวจจากเนื้อไฟล์จริง
|
|
const type = sniffImageType(bytes);
|
|
if (!type || !isValidImageUpload(bytes)) {
|
|
throw createError({
|
|
statusCode: 415,
|
|
statusMessage: "รับเฉพาะรูป JPEG / PNG / WebP / AVIF",
|
|
});
|
|
}
|
|
|
|
const slugPart = parts?.find((part) => part.name === "slug")?.data;
|
|
const slug = slugPart ? Buffer.from(slugPart).toString("utf8") : "cinema";
|
|
const fileName = makeUploadName(slug, type);
|
|
|
|
await fs.mkdir(UPLOAD_DIR, { recursive: true });
|
|
await fs.writeFile(path.join(UPLOAD_DIR, fileName), bytes);
|
|
|
|
return {
|
|
url: `${UPLOAD_URL_PREFIX}/${fileName}`,
|
|
bytes: bytes.byteLength,
|
|
type,
|
|
};
|
|
});
|