Unable to send date via postForm in axios

87 Views Asked by At

Description of the issue

I am working on a nextjs project. The problem is when I am posting multiple images array via postForm is not working but if I use postForm.append then those image arrays are working properly.

axios version : "1.6.1",

This is an example of posting via Axios postForm

   const images = [File, File, File]
   const res = await axios.postForm("/example",images)

This is Example of posting old process

const postForm = new FormData();
   images.forEach((img) => {
      postFrom.append("images", img);
    });

How to solve this problem.

1

There are 1 best solutions below

1
On

Here's how you can modify your code to use axios.post and FormData:

// Assuming images is an array of File objects
const images = [File, File, File];

const postForm = new FormData();

images.forEach((img, index) => {
  postForm.append(`images[${index}]`, img);
});

// Make the POST request using axios.post
try {
  const response = await axios.post("/example", postForm, {
    headers: {
      "Content-Type": "multipart/form-data", //form-data
    },
  });

  console.log(response.data);
   } catch (error) {
  console.error("Error posting images:", error);
}

Make sure to use axios.post instead of axios.postForm. Also, ensure that you set the correct Content-Type header for the FormData object, as shown in the above snippet.