feat: refactor file download to use MinIO for file retrieval

This commit is contained in:
ZareMate 2025-05-12 07:12:43 +02:00
parent 453264d9cd
commit 82d1e74af1
Signed by: zaremate
GPG Key ID: 369A0E45E03A81C3

View File

@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import path from "path";
import { promises as fs } from "fs";
import { db } from "~/server/db";
import { minioClient } from "~/utils/minioClient";
export async function GET(req: Request) {
const url = new URL(req.url);
@ -10,22 +10,43 @@ export async function GET(req: Request) {
if (!fileId) {
return NextResponse.json({ error: "File id is required" }, { status: 400 });
}
if (!fileName){
if (!fileName) {
return NextResponse.json({ error: "File name is required" }, { status: 400 });
}
try {
const filePath = path.join(process.cwd(), "uploads", fileId);
const fileBuffer = await fs.readFile(filePath);
// Fetch file metadata from the database
const file = await db.file.findFirst({
where: { id: fileId },
});
return new Response(fileBuffer, {
if (!file) {
return NextResponse.json({ error: "File not found" }, { status: 404 });
}
const bucketName = process.env.MINIO_BUCKET || "file-hosting";
const objectName = `${file.id}-${file.name}`; // Construct the object name in MinIO
// Fetch the file from MinIO
const stream = await minioClient.getObject(bucketName, objectName);
// Return the file as a binary response
const readableStream = new ReadableStream({
start(controller) {
stream.on("data", (chunk) => controller.enqueue(chunk));
stream.on("end", () => controller.close());
stream.on("error", (err) => controller.error(err));
},
});
return new Response(readableStream, {
headers: {
"Content-Type": "application/octet-stream",
"Content-Disposition": `attachment; filename="${fileName}" , fileId="${fileId}"`,
"Content-Disposition": `attachment; filename="${fileName}"`,
},
});
} catch (error) {
console.error("Error reading file:", error);
return NextResponse.json({ error: "File not found" }, { status: 404 });
console.error("Error fetching file from MinIO:", error);
return NextResponse.json({ error: "Failed to fetch file" }, { status: 500 });
}
}