Next.js Discord

Discord Forum

its possible send multipart data from API to Client?

Unanswered
Phainopepla posted this in #help-forum
Open in Discord
PhainopeplaOP
Hello, im building a customer info reviewer for my app, the sending of data and storage of files its already done, but now i have some troubles to bring back to client the files from the API GET call about his information

Some of my troubles are about the right way to return a multipart contentType to client, also the fact that from server side i cant build the File type, so it must be sent as Buffer

Here is my attemp to solve it using a simple formData object

import { getObject } from "@/services/s3Client";
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const folderPrefix = searchParams.get("customerId");

  if (!folderPrefix) {
    return NextResponse.json({ success: false, error: "Customer Id must be indicated" })
  };

  try {
    const keys = ["1/100.pdf", "1/101.jpg", "1/92.pdf"];

    const boundary = 'boundary-' + Math.random().toString().substr(2);

    const response = new NextResponse();

    response.headers.set('Content-Type', `multipart/mixed; boundary=${boundary}`);

    let responseBody = '';

    // for each key, get the object and add part to multipart
    for (const key of keys) {
      const { content, contentType } = await getObject({ key });

      // add part to multipart
      responseBody += `--${boundary}\r\n`;
      responseBody += `Content-Type: ${contentType}\r\n`;
      responseBody += `Content-Disposition: attachment; filename="${key}"\r\n\r\n`;
      responseBody += content.toString('binary');
      responseBody += '\r\n';
    }

    // Finalizar el multipart
    responseBody += `--${boundary}--`;

    response.write(responseBody, 'binary');

    return response;
  } catch (error) {
    return NextResponse.json({ success: false, error: "Error fetching the objects" });
  }
}

0 Replies