feat: Implement file upload structure and API for file retrieval

This commit is contained in:
2025-09-16 11:27:25 +02:00
parent e5955a31fd
commit 06599c844a
9 changed files with 76 additions and 1 deletions

View File

@@ -1,8 +1,58 @@
import { NextResponse } from "next/server";
import { readFile } from "fs/promises";
import { existsSync } from "fs";
import { unlink } from "fs/promises";
import path from "path";
import db from "@/lib/db";
export async function GET(request, { params }) {
try {
const fileId = params.fileId;
// Get file info from database
const file = db.prepare(`
SELECT * FROM file_attachments WHERE file_id = ?
`).get(parseInt(fileId));
if (!file) {
return NextResponse.json(
{ error: "File not found" },
{ status: 404 }
);
}
// Construct the full file path
const fullPath = path.join(process.cwd(), "public", file.file_path);
// Check if file exists
if (!existsSync(fullPath)) {
return NextResponse.json(
{ error: "File not found on disk" },
{ status: 404 }
);
}
// Read the file
const fileBuffer = await readFile(fullPath);
// Return the file with appropriate headers
return new NextResponse(fileBuffer, {
headers: {
"Content-Type": file.mime_type || "application/octet-stream",
"Content-Disposition": `attachment; filename="${encodeURIComponent(file.original_filename)}"`,
"Content-Length": fileBuffer.length.toString(),
},
});
} catch (error) {
console.error("Error downloading file:", error);
return NextResponse.json(
{ error: "Failed to download file" },
{ status: 500 }
);
}
}
export async function DELETE(request, { params }) {
try {
const fileId = params.fileId;