elias-soykat
elias-soykat

Reputation: 139

How to handle multipart formData in next.js 14 server actions

Here is my Next.js page.jsx file code where i handle a form file using browser new FormData() web api and this uploadImageConverter function is a server actions function.

 "use client"

  const handleFileUpload = (e) => {
    setImage(URL.createObjectURL(e.target.files[0]));
    setState({ ...state, file: e.target.files[0] });
  };

  const handleSubmitForm = async (e) => {
    const formData = new FormData();

    try {
      formData.append("image", state.file);

      const response = await uploadImageConverter(formData);

      console.log(`page.js:26 response ==>>`, response);
    } catch (err) {
      console.error("Error uploading image:", err);
    }
  };

Below function code will execuete in the server how to get the req property in the server side or how to get the file path like //'C:\\Users\\elias\\AppData\\Local\\Temp\\upload_90d3ba8ab6c800c51fb74753c146236d'

"use server";

import formidable from "formidable";
import sharp from "sharp";

export async function uploadImageConverter(formData) {
  return new Promise((resolve, reject) => {
    const f = formidable();

    f.parse(formData, async (err, fields, files) => {
      if (err) {
        reject(err);
        return;
      }

      const imageInput = files.image.path; //'C:\\Users\\elias\\AppData\\Local\\Temp\\upload_90d3ba8ab6c800c51fb74753c146236d',
      const contentType = files.image.type;

      try {
        const resizedImageBuffer = await sharp(imageInput)
          .resize(512, 512)
          .png()
          .toBuffer();

        resolve({
          data: resizedImageBuffer.toString("base64"),
          contentType: contentType,
          extension: "png",
        });
      } catch (err) {
        reject(err);
      }
    });
  });
}

I'm try to use next.js 14 server actions to handle the multipart formData where i can get the file path that is very similar to using formidable when i used to express.js but how to get the next.js 14 server actions?

Upvotes: 4

Views: 591

Answers (0)

Related Questions