61 lines
1.5 KiB
JavaScript
61 lines
1.5 KiB
JavaScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { readFile } from "fs/promises";
|
|
import { existsSync } from "fs";
|
|
import path from "path";
|
|
import db from "@/lib/db";
|
|
|
|
export async function GET(request, { params }) {
|
|
try {
|
|
const { filename } = params;
|
|
|
|
if (!filename) {
|
|
return NextResponse.json(
|
|
{ error: "Filename is required" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Get template info from database
|
|
const template = db.prepare(`
|
|
SELECT * FROM docx_templates WHERE stored_filename = ? AND is_active = 1
|
|
`).get(filename);
|
|
|
|
if (!template) {
|
|
return NextResponse.json(
|
|
{ error: "Template not found" },
|
|
{ status: 404 }
|
|
);
|
|
}
|
|
|
|
// Check if file exists
|
|
const filePath = path.join(process.cwd(), "templates", filename);
|
|
if (!existsSync(filePath)) {
|
|
return NextResponse.json(
|
|
{ error: "Template file not found" },
|
|
{ status: 404 }
|
|
);
|
|
}
|
|
|
|
// Read file
|
|
const fileBuffer = await readFile(filePath);
|
|
|
|
// Return file with proper headers
|
|
const response = new NextResponse(fileBuffer, {
|
|
status: 200,
|
|
headers: {
|
|
"Content-Type": template.mime_type || "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
"Content-Disposition": `attachment; filename="${template.original_filename}"`,
|
|
"Content-Length": fileBuffer.length.toString(),
|
|
},
|
|
});
|
|
|
|
return response;
|
|
|
|
} catch (error) {
|
|
console.error("Template download error:", error);
|
|
return NextResponse.json(
|
|
{ error: "Failed to download template" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
} |