first commit

This commit is contained in:
Johan LEROY
2026-04-21 14:14:03 +02:00
commit 7c7ff160eb
125 changed files with 13379 additions and 0 deletions

41
src/pages/api/upload.ts Normal file
View File

@@ -0,0 +1,41 @@
export const prerender = false;
import type { APIRoute } from 'astro';
import { writeFile, mkdir } from 'node:fs/promises';
import { join, extname, basename } from 'node:path';
const UPLOAD_DIR = join(process.cwd(), 'public', 'img');
const ALLOWED_EXT = new Set(['.png', '.jpg', '.jpeg', '.webp', '.svg', '.gif']);
function sanitize(filename: string): string {
const name = basename(filename).replace(/[^a-zA-Z0-9._-]/g, '_');
return name.slice(-120);
}
export const POST: APIRoute = async ({ request }) => {
const form = await request.formData();
const file = form.get('file');
const folder = (form.get('folder') as string | null) ?? '';
if (!(file instanceof File)) {
return new Response(JSON.stringify({ error: 'no_file' }), { status: 400 });
}
const ext = extname(file.name).toLowerCase();
if (!ALLOWED_EXT.has(ext)) {
return new Response(JSON.stringify({ error: 'invalid_extension' }), { status: 400 });
}
const safeFolder = folder.replace(/[^a-zA-Z0-9_-]/g, '');
const targetDir = safeFolder ? join(UPLOAD_DIR, safeFolder) : UPLOAD_DIR;
await mkdir(targetDir, { recursive: true });
const filename = sanitize(file.name);
const buffer = Buffer.from(await file.arrayBuffer());
await writeFile(join(targetDir, filename), buffer);
const url = `/img/${safeFolder ? safeFolder + '/' : ''}${filename}`;
return new Response(JSON.stringify({ ok: true, url }), {
headers: { 'Content-Type': 'application/json' },
});
};