Next.js Discord

Discord Forum

upload file to cloudinary through next js enpoint

Unanswered
Iridescent shark posted this in #help-forum
Open in Discord
Iridescent sharkOP
I have an react component which uploads files to cloudinary with axios through my own web api endpoint. Overall process goes: axios post request to localhost/api/files/upload then at this endpoint I send files to cloudinary with this code:
export async function POST(req: NextRequest) {
  try {
    const formData = await req.formData();
    const formDataEntryValues = Array.from(formData.values());
    for (const formDataEntryValue of formDataEntryValues) {
      if (typeof formDataEntryValue === "object" && "arrayBuffer" in formDataEntryValue) {
        const file = formDataEntryValue as unknown as Blob;

        if (file.size > config.maxFileSize) {
          return BadRequest(`Max file size is ${config.maxFileSizeAsString}`);
        }

        const buffer = Buffer.from(await file.arrayBuffer());
        const response = await uploadWrapper(buffer);

        return NextResponse.json(response, { status: 200 });
      }
    }
  } catch (error: any) {
    return NextResponse.json(error, { status: 500 });
  }
}

const uploadWrapper = async (buffer: Buffer) => {
  return new Promise(async (resolve, reject) => {
// Here I stream file with cloudinary's library
    const cloud_upload_stream = await cloudinary.v2.uploader.upload_stream({
      folder: config.storePath
    }, (error, result) => {
      if (error) {
        reject(error);
      } else {
        resolve(result);
      }
    });
    streamifier.createReadStream(buffer).pipe(cloud_upload_stream);
  })
}

The problem is that axios show progress while I upload file to my endpoint, at 100% I need to await more for file being uploaded to cloudinary. How I can pass through axiosProgressEvent the time user need to wait for file uploading to clouinary?

0 Replies