40 lines
1.2 KiB
JavaScript
40 lines
1.2 KiB
JavaScript
|
|
import { NextResponse } from "next/server";
|
||
|
|
import fs from "fs";
|
||
|
|
import path from "path";
|
||
|
|
|
||
|
|
export async function GET(request, { params }) {
|
||
|
|
try {
|
||
|
|
const paths = (await params).path.join("/");
|
||
|
|
const fullpath = path.join(process.cwd(), "/public/media", paths);
|
||
|
|
|
||
|
|
if (!fs.existsSync(fullpath))
|
||
|
|
return NextResponse.json({ error: "not found" }, { status: 404 });
|
||
|
|
|
||
|
|
const fileBuffer = fs.readFileSync(fullpath);
|
||
|
|
const filestat = fs.statSync(fullpath);
|
||
|
|
const ext = path.extname(fullpath).toLowerCase();
|
||
|
|
const mimeTypes = {
|
||
|
|
".jpg": "image/jpeg",
|
||
|
|
".jpeg": "image/jpeg",
|
||
|
|
".png": "image/png",
|
||
|
|
".gif": "image/gif",
|
||
|
|
".webp": "image/webp",
|
||
|
|
".svg": "image/svg+xml",
|
||
|
|
};
|
||
|
|
|
||
|
|
return new NextResponse(fileBuffer, {
|
||
|
|
status: 200,
|
||
|
|
headers: {
|
||
|
|
"Content-Type": mimeTypes[ext] || "application/octet-stream",
|
||
|
|
"Access-Control-Allow-Origin": "*",
|
||
|
|
"Content-Length": filestat.size.toString(),
|
||
|
|
"Cache-Control": "public, max-age=31536000, immutable",
|
||
|
|
"Last-Modified": filestat.mtime.toUTCString(),
|
||
|
|
ETag: `"${filestat.mtime.getTime()}-${filestat.size}"`,
|
||
|
|
},
|
||
|
|
});
|
||
|
|
} catch (error) {
|
||
|
|
return NextResponse.json({ error: error.message }, { status: 404 });
|
||
|
|
}
|
||
|
|
}
|