Add server route to serve uploaded files in production
Deploy to LXC / deploy (push) Successful in 17s
Deploy to LXC / deploy (push) Successful in 17s
adapter-node only serves pre-built static assets, not files uploaded at runtime. Added /uploads/[...path] catch-all route that reads from static/uploads/ with proper MIME types and cache headers. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,40 @@
|
|||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { readFile } from 'fs/promises';
|
||||||
|
import { join, extname } from 'path';
|
||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
const MIME_TYPES: Record<string, string> = {
|
||||||
|
'.jpg': 'image/jpeg',
|
||||||
|
'.jpeg': 'image/jpeg',
|
||||||
|
'.png': 'image/png',
|
||||||
|
'.webp': 'image/webp',
|
||||||
|
'.gif': 'image/gif',
|
||||||
|
'.svg': 'image/svg+xml',
|
||||||
|
'.pdf': 'application/pdf',
|
||||||
|
'.txt': 'text/plain',
|
||||||
|
'.zip': 'application/zip'
|
||||||
|
};
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ params }) => {
|
||||||
|
const filePath = params.path;
|
||||||
|
|
||||||
|
// Prevent directory traversal
|
||||||
|
if (filePath.includes('..')) error(400, 'Invalid path');
|
||||||
|
|
||||||
|
const fullPath = join('static', 'uploads', filePath);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await readFile(fullPath);
|
||||||
|
const ext = extname(filePath).toLowerCase();
|
||||||
|
const contentType = MIME_TYPES[ext] ?? 'application/octet-stream';
|
||||||
|
|
||||||
|
return new Response(data, {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': contentType,
|
||||||
|
'Cache-Control': 'public, max-age=86400'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
error(404, 'File not found');
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user