Untitled

 avatar
unknown
plain_text
2 months ago
2.2 kB
5
Indexable
// app/api/download/[clientId]/route.ts
import { NextResponse } from "next/server";
import { createReadStream, existsSync } from "fs";
import { mkdir, readdir } from "fs/promises";
import { join } from "path";
import archiver from "archiver";
import { Stream } from "stream";

export async function GET(
  request: Request,
  { params }: { params: { clientId: string } }
) {
  try {
    const clientId = params.clientId;
    const imagesDir = join(process.cwd(), "public", "clients", clientId, "images");

    // Check if directory exists
    if (!existsSync(imagesDir)) {
      return NextResponse.json(
        { error: "Client directory not found" },
        { status: 404 }
      );
    }

    // Get all images from the directory
    const files = await readdir(imagesDir);
    const imageFiles = files.filter(file => 
      /\.(jpg|jpeg|png|webp)$/i.test(file)
    );

    if (imageFiles.length === 0) {
      return NextResponse.json(
        { error: "No images found" },
        { status: 404 }
      );
    }

    // Create response stream
    const stream = new Stream.PassThrough();
    const archive = archiver("zip", {
      zlib: { level: 5 } // Compression level (1-9)
    });

    // Set up archive error handling
    archive.on("error", (err) => {
      console.error("Archive error:", err);
      throw err;
    });

    // Pipe archive data to response stream
    archive.pipe(stream);

    // Add each image to the archive
    for (const file of imageFiles) {
      const filePath = join(imagesDir, file);
      archive.append(createReadStream(filePath), { name: file });
    }

    // Finalize the archive
    await archive.finalize();

    // Create the response with appropriate headers
    const response = new NextResponse(stream as any);
    response.headers.set("Content-Type", "application/zip");
    response.headers.set("Content-Disposition", `attachment; filename=${clientId}-photos.zip`);
    
    return response;
  } catch (error) {
    console.error("Download error:", error);
    return NextResponse.json(
      { error: "Failed to create download" },
      { status: 500 }
    );
  }
}
Editor is loading...
Leave a Comment