Port image routes

This commit is contained in:
2026-01-30 14:18:39 +13:00
parent 11bb625a97
commit 7e574719f8
2 changed files with 72 additions and 0 deletions

View File

@@ -0,0 +1,37 @@
import { UPLOAD_DIR } from '$env/static/private'
import { promises as fs } from "fs"
import { join } from 'path'
import { randomBytes } from 'crypto';
import { httpResponse } from '$lib/server/http';
export async function POST({ request }) {
try {
const formData = await request.formData();
const file = formData.get('image');
return await writeImage(file as File)
} catch (error) {
return httpResponse({ error: `Failed to upload image, ${error}` }, 500);
}
}
async function writeImage(file: File) {
if (!file || !(file instanceof File)) {
return httpResponse({ error: 'No image provided' }, 400);
}
if (!file.type.match(/^image\/(jpeg|jpg|png)$/)) {
return httpResponse({ error: 'Only JPG and PNG allowed' }, 400);
}
const ext = file.name.split('.').pop();
const filename = `${randomBytes(16).toString('hex')}.${ext}`;
const filepath = join(UPLOAD_DIR, filename);
// Save file
const buffer = Buffer.from(await file.arrayBuffer());
await fs.writeFile(filepath, buffer);
return httpResponse({ url: `/api/image/${filename}`}, 201);
}

View File

@@ -0,0 +1,35 @@
import { UPLOAD_DIR } from '$env/static/private'
import { promises as fs } from "fs"
import { join } from 'path'
import { httpResponse } from '$lib/server/http';
export async function GET({ params }) {
try {
const { id } = params
return readImage(id!)
} catch (error) {
return httpResponse({ error: `Failed to retrieve image: ${error}` }, 500);
}
}
async function readImage(id: string) {
const filepath = join(UPLOAD_DIR, id);
try {
await fs.access(filepath);
} catch {
return httpResponse({ error: 'Image not found' }, 404);
}
const image = await fs.readFile(filepath);
const ext = id.split('.').pop()?.toLowerCase();
const contentType = ext === 'png' ? 'image/png' : 'image/jpeg';
return new Response(image, {
status: 200,
headers: {
'Content-Type': contentType,
}
});
}