Unexpected end of form at Multipart._final
Asked Answered
S

1

4

I have multiple inputs and the upload is working fine when all the image input fields are filled. But if any of them is empty, it throws an error in my server side "Unexpected end of form at mutipart".

This is the Client Side:

 const handelSubmit = (e) => {
    e.preventDefault();

    const formData = new FormData();
    formData.append("portOne", portOne);
    formData.append("portTwo", portTwo);
    formData.append("portThree", portThree);
    formData.append("portFour", portFour);

    axios
      .post("http://localhost:5000/set-portfolio", formData)
      .then((result) => {})
      .catch((err) => {
        console.log(err);
      });
  };

Server Side code

const uploadField = upload.fields([
  { name: "portOne" },
  { name: "portTwo" },
  { name: "portThree" },
  { name: "portFour" },
]);

uploadField(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      console.log(err);
    } else if (err) {
      console.log(err);
    }

    const imgObj = JSON.parse(JSON.stringify(req.files));
    const imgObjectLength = Object.keys(imgObj).length;

    const portOne = imgObj.portOne[0].path;
    const portTwo = imgObj.portTwo[0].path;
    const portThree = imgObj.portThree[0].path;
    const portFour = imgObj.portFour[0].path;
Sewoll answered 6/6, 2022 at 8:43 Comment(2)
try to add conditional on client side, before appending to formData. And update the server side.Transmissible
This is the solution I used and it worked for me; Solution to "unexpetcted end of form" errorWouldst
L
0

You can modify your handleSubmit function to check if each field has a value before appending it to FormData.

const handelSubmit = (e) => {
  e.preventDefault();

  const formData = new FormData();

  // Assuming portOne, portTwo, portThree, portFour are state variables
  // If any of them is empty, it won't be appended to FormData
  if (portOne) formData.append("portOne", portOne);
  if (portTwo) formData.append("portTwo", portTwo);
  if (portThree) formData.append("portThree", portThree);
  if (portFour) formData.append("portFour", portFour);

  axios
    .post("http://localhost:5000/set-portfolio", formData)
    .then((result) => {})
    .catch((err) => {
      console.log(err);
    });
};
Lothar answered 2/2 at 13:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.