feat: Implement file upload structure and API for file retrieval
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -149,7 +149,7 @@ export default function FileAttachmentsList({ entityType, entityId, onFilesChang
|
||||
</div>
|
||||
<div className="flex items-center gap-2 ml-3">
|
||||
<a
|
||||
href={file.file_path}
|
||||
href={`/api/files/${file.file_id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:text-blue-800"
|
||||
|
||||
Reference in New Issue
Block a user