Next.js Discord

Discord Forum

Image compression before upload (POST 413 ERROR)

Unanswered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
I built a page on my site that allows my client to add a product to his database. On this page I have 2 inputs that are files. Product Image (s) & Nutrition label.

async function uploadNL(
  nutritionLabel: FormDataEntryValue,
  brand: string,
  name: string
): Promise<string> { // Specify that the function returns a Promise<string>
  "use server";

  const formData = new FormData();
  formData.append("file", nutritionLabel);
  formData.append("upload_preset", "dkfnb2cn");
  formData.append("folder", `${brand}/${name}/NutritionFacts`);

  // Return the Promise from axios.post
  return axios.post("api", formData)
    .then((response) => {
      console.log(response.data.url);
      return response.data.url;
    })
    .catch((error) => {
      console.log(error);
      return ''; // Return an empty string or handle the error accordingly
    });
}

async function uploadImages(
  files: FormDataEntryValue[],
  brand: string,
  name: string
) {
  "use server";
  
  let urls: string[] = [];
  const uploadPromises: Promise<void>[] = [];

  //first upload all files
  for (const file of files) {
    // let i = 0;
    const formData = new FormData();
    formData.append("file", file);
    formData.append("upload_preset", "dkfnb2cn");
    formData.append("folder", `${brand}/${name}`);
    // formData.append("filename_override", `${name}` + i.toString)

    const uploadPromise = axios
      .post("api", formData)
      .then((response) => {
        console.log(response.data.url);
        urls.push(response.data.url);
      })
      .catch((error) => {
        console.log(error);
      });

    uploadPromises.push(uploadPromise);
  }

  // Wait for all upload promises to resolve
  await Promise.all(uploadPromises);

  return urls;
}


when i test on localhost i can upload as many pictures as i want, however, when deployed on vercel, I get a POST 413 error when trying to upload too many files.

What can I do here?

1 Reply

you need to host it on other cloud venders such as AWS as you seem to hit the payload size cap
https://vercel.com/docs/concepts/limits/overview#serverless-function-payload-size-limit