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;
brohxa
  • 89
  • 1
  • 9
  • try to add conditional on client side, before appending to `formData`. And update the server side. – Stefan Jun 06 '22 at 09:49
  • 1
    This is the solution I used and it worked for me; [Solution to "unexpetcted end of form" error](https://stackoverflow.com/questions/72887603/how-to-solve-multer-error-unexpected-end-of-form) – Joshua Oweipadei Dec 20 '22 at 03:27

0 Answers0