Does anyone try formidable npm package to upload multiple images? I need an immediate help

I have been trying to create seperate code for both of my files but no Luck !!! I need an immediate help.

If your talking about this:

no, but to help debug the issue you should provide the following:

  1. What code do you have so far?
  2. What have you tried?
  3. Are you getting errors? If so, what?
  4. What are you trying to do overall with the library? Where are you trying to upload images?
  1. `router.post(’/Customer/personalinfo’, async (req, res) => {
    const formData = formidable({
    multiples: true,
    uploadDir: ‘./public/Customer/’,
    });

formData.parse(req, async (error, fields, files) => {
const { firstname ,
lastname,
middlename,
fathername,
spousename,
gender,
meritalstatus,
dateofbirth,
dateofissuance,
dateofexpiry,
organization,
emailaddress,
city,
province,
cnic,
contactno} = fields;

const {cnicfrontendimage,cnicbackendimage} =files;

if (
!firstname||
!lastname ||
! middlename ||
!fathername ||
!spousename ||
!gender ||
!meritalstatus||
!dateofbirth||
!dateofissuance ||
!dateofexpiry ||
!organization ||
!emailaddress ||
!cnicfrontendimage||
!cnicbackendimage||
!city ||
!province ||
!cnic ||
!contactno
) {
return res
.status(400)
.json({ success: false, message: ‘All fields are required.’ });
}

try {
const newCustomer = await Customer.create({
firstname ,
lastname,
middlename,
fathername,
spousename,
gender,
meritalstatus,
dateofbirth,
dateofissuance,
dateofexpiry,
organization,
emailaddress,
city,
province,
cnic,
cnicfrontendimage,
cnicbackendimage,
contactno
});

// Extract extension, path and type of images for frontendurl
const imageExtension = cnicfrontendimage.name.substr(cnicfrontendimage.name.lastIndexOf('.'));
const imagePath = './public/Customer/cnicfrontendimage_' + newCustomer._cnic + imageExtension;
const imageType = cnicfrontendimage.type.split('/').pop();

// Check license image type
if (imageType !== 'jpeg' && imageType !== 'jpg' && imageType !== 'png')
  throw 'image type must be jpeg, jpg or png';

// Store License
fs.rename(cnicfrontendimage.path, imagePath, (errorRename) => {
  if (errorRename) {
    throw 'image store error';
  }
});
  const updatedfrontendimage = await Customer.findAndUpload(
  { _id: newfrontendimage._id },
  {
    cnicfrontendUrl: `Customer/cnicfrontendimage_${newfrontendimage._id}${imageExtension}`,
  },
  
  { new: true },
);

return res.status(200).json({ success: true, message: updatedfrontendimage});

} catch (error) {
fs.unlinkSync(updatedfrontendimage.path);
console.log(‘catch’);
console.log(error);
return res.status(400).json({ success: false, message: error });
}
});
// Extract extension, path and type of images for backendurl
const imageExtension = cnicbackendimage.name.substr(cnicbackendimage.name.lastIndexOf(’.’));
const imagePath = ‘./public/Customer/cnicbackendimage_’ + newCustomer._cnic + imageExtension;
const imageType = cnicbackendimage.type.split(’/’).pop();

// Check license image type
if (imageType !== ‘jpeg’ && imageType !== ‘jpg’ && imageType !== ‘png’)
throw ‘image type must be jpeg, jpg or png’;

// Store License
fs.rename(cnicbackendimage.path, imagePath, (errorRename) => {
if (errorRename) {
throw ‘image store error’;
}
});
const updatedbackendimage = await Customer.findAndUpload(
{ _id: newbackendimage._id },
{
cnicbackendUrl: Customer/cnicbackendimage_${newbackendimage._id}${imageExtension},
},

{ new: true },

);

return res.status(200).json({ success: true, message: updatedbackendimage});
}) catch (error) {
fs.unlinkSync(updatedbackendimage.path);
console.log(‘catch’);
console.log(error);
return res.status(400).json({success:false, message: error});
}
module.exports = router; 2) I have been trying to upload the front and backend image of the national identity card using an API I have created to create a data form using formidable. 3)Yes , I m getting errors when I execute my Api form on swagger .![image|690x298](upload://rtAFtA42rXTB15TLP9Hz1xX6daS.png) 4) I'm trying to create a data-form using POST request and trying to upload 2 images on the same from. ![image|584x500](upload://jjAQZhDOMMH05HHrz23m5jcfsPt.png) It throws this error when I run it withcatch(error)` .Hope ,It make sense to you!

  1. router.post(’/Customer/personalinfo’, async (req, res) => {
    const formData = formidable({
    multiples: true,
    uploadDir: ‘./public/Customer/’,
    });

formData.parse(req, async (error, fields, files) => {
const { firstname ,
lastname,
middlename,
fathername,
spousename,
gender,
meritalstatus,
dateofbirth,
dateofissuance,
dateofexpiry,
organization,
emailaddress,
city,
province,
cnic,
contactno} = fields;

const {cnicfrontendimage,cnicbackendimage} =files;

if (
!firstname||
!lastname ||
! middlename ||
!fathername ||
!spousename ||
!gender ||
!meritalstatus||
!dateofbirth||
!dateofissuance ||
!dateofexpiry ||
!organization ||
!emailaddress ||
!cnicfrontendimage||
!cnicbackendimage||
!city ||
!province ||
!cnic ||
!contactno
) {
return res
.status(400)
.json({ success: false, message: ‘All fields are required.’ });
}

try {
const newCustomer = await Customer.create({
firstname ,
lastname,
middlename,
fathername,
spousename,
gender,
meritalstatus,
dateofbirth,
dateofissuance,
dateofexpiry,
organization,
emailaddress,
city,
province,
cnic,
cnicfrontendimage,
cnicbackendimage,
contactno
});

// Extract extension, path and type of images for frontendurl
const imageExtension = cnicfrontendimage.name.substr(cnicfrontendimage.name.lastIndexOf('.'));
const imagePath = './public/Customer/cnicfrontendimage_' + newCustomer._cnic + imageExtension;
const imageType = cnicfrontendimage.type.split('/').pop();

// Check license image type
if (imageType !== 'jpeg' && imageType !== 'jpg' && imageType !== 'png')
  throw 'image type must be jpeg, jpg or png';

// Store License
fs.rename(cnicfrontendimage.path, imagePath, (errorRename) => {
  if (errorRename) {
    throw 'image store error';
  }
});
  const updatedfrontendimage = await Customer.findAndUpload(
  { _id: newfrontendimage._id },
  {
    cnicfrontendUrl: `Customer/cnicfrontendimage_${newfrontendimage._id}${imageExtension}`,
  },
  
  { new: true },
);

return res.status(200).json({ success: true, message: updatedfrontendimage});

} catch (error) {
fs.unlinkSync(updatedfrontendimage.path);
console.log(‘catch’);
console.log(error);
return res.status(400).json({ success: false, message: error });
}
});
// Extract extension, path and type of images for backendurl
const imageExtension = cnicbackendimage.name.substr(cnicbackendimage.name.lastIndexOf(’.’));
const imagePath = ‘./public/Customer/cnicbackendimage_’ + newCustomer._cnic + imageExtension;
const imageType = cnicbackendimage.type.split(’/’).pop();

// Check license image type
if (imageType !== ‘jpeg’ && imageType !== ‘jpg’ && imageType !== ‘png’)
throw ‘image type must be jpeg, jpg or png’;

// Store License
fs.rename(cnicbackendimage.path, imagePath, (errorRename) => {
if (errorRename) {
throw ‘image store error’;
}
});
const updatedbackendimage = await Customer.findAndUpload(
{ _id: newbackendimage._id },
{
cnicbackendUrl: Customer/cnicbackendimage_${newbackendimage._id}${imageExtension} ,
},

{ new: true },

);

return res.status(200).json({ success: true, message: updatedbackendimage});
}) catch (error) {
fs.unlinkSync(updatedbackendimage.path);
console.log(‘catch’);
console.log(error);
return res.status(400).json({success:false, message: error});
}
module.exports = router;
2) I have been trying to upload the front and backend image of the national identity card using an API I have created to create a data form using formidable.
3)Yes , I m getting errors when I execute my Api form on swagger .

4) I’m trying to create a data-form using POST request and trying to upload 2 images on the same from. It throws this error when I run it with catch(error) .Hope ,It make sense to you!

@bradtaniguchi please read my comments.

It looks like you forgot to format your code.

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

So there are a few things worth pointing out, not all related to the error, but are still something you should look into.

  1. What happened to the code formatting?

Formatting your code (or using a tool that can format it for you) is so you can read it better and understand how it works. The computer doesn’t care about how the code is formatted, so its there just for you. Especially in a case like this were the code effectively doesn’t even run due to syntax issues, having your code formatted should help you spot the issue faster.

  1. Your mixing different quotes with this character:

according to bablestone this is: U+2019 : RIGHT SINGLE QUOTATION MARK {single comma quotation mark}

which isn’t one of the following:

' - single quote
" - double quote
` - backtick

I don’t have the “right single quotation mark” on my keyboard, so I have to copy and paste it here. However, I think using it in the code might result in funky behavior down the line, or at least confuse other developers. I originally tried to format one of your posts using prettier and wasn’t able to due to the “right single quotation mark” not being recognized.

Your mixing that “right single quotation mark” with the the single quote often within the code, and since visually they look really similar this is just bugs waiting to happen.

  1. At a quick glance the issue boils down to having 2 catch calls, with only one try. I would go further into other issues but due to the code not being formatted, its unfortunately not clear what your trying to do or how your trying to handle it.

Id suggest to reformat the code, and possibly re-write it from scratch so its formatted and follows the same original logic you set out to write.

1 Like

@bradtaniguchi please check my code now.

router.post('/Customer/personalinfo', async (req, res) => {
  const formData = formidable({
    multiples: true,
    uploadDir: './public/Customer/',
  });

  formData.parse(req, async (error, fields, files) => {
    const { firstname , 
      lastname, 
      middlename, 
      fathername,
      spousename,
      gender,
      meritalstatus,
      dateofbirth,
      dateofissuance,
      dateofexpiry,
      organization,
      emailaddress,
      city,
      province,
      cnic,
      contactno} = fields;

   const {cnicfrontendimage,cnicbackendimage} =files;

  if (
    !firstname||
    !lastname ||
    ! middlename ||
    !fathername ||
    !spousename ||
    !gender ||
    !meritalstatus||
    !dateofbirth||
    !dateofissuance ||
    !dateofexpiry ||
    !organization ||
    !emailaddress ||
    !cnicfrontendimage||
    !cnicbackendimage||
    !city ||
    !province ||
    !cnic ||
    !contactno
  ) {
    return res
      .status(400)
      .json({ success: false, message: 'All fields are required.' });
  }
  
  try {
    const newCustomer = await Customer.create({
      firstname , 
      lastname, 
      middlename, 
      fathername,
      spousename,
      gender,
      meritalstatus,
      dateofbirth,
      dateofissuance,
      dateofexpiry,
      organization,
      emailaddress,
      city,
      province,
      cnic,
      cnicfrontendimage,
      cnicbackendimage,
      contactno
    });

    // Extract extension, path and type of images for frontendurl
    const imageExtension = cnicfrontendimage.name.substr(cnicfrontendimage.name.lastIndexOf('.'));
    const imagePath = './public/Customer/cnicfrontendimage_' + newCustomer._cnic + imageExtension;
    const imageType = cnicfrontendimage.type.split('/').pop();

    // Check license image type
    if (imageType !== 'jpeg' && imageType !== 'jpg' && imageType !== 'png')
      throw 'image type must be jpeg, jpg or png';

    // Store License
    fs.rename(cnicfrontendimage.path, imagePath, (errorRename) => {
      if (errorRename) {
        throw 'image store error';
      }
    });
      const updatedfrontendimage = await Customer.findAndUpload(
      { _id: newfrontendimage._id },
      {
        cnicfrontendUrl: `Customer/cnicfrontendimage_${newfrontendimage._id}${imageExtension}`,
      },
      
      { new: true },
    );

    return res.status(200).json({ success: true, message: updatedfrontendimage});
   
    }catch (error) {
    fs.unlinkSync(updatedfrontendimage.path);
    console.log('catch');
   console.log(error);
    return res.status(400).json({ success: false, message: error });
  } 
    }); 
  
  

 
  // Extract extension, path and type of images for backendurl
  const imageExtension = cnicbackendimage.name.substr(cnicbackendimage.name.lastIndexOf('.'));
  const imagePath = './public/Customer/cnicbackendimage_' + newCustomer._cnic + imageExtension;
  const imageType = cnicbackendimage.type.split('/').pop();

  // Check license image type
  if (imageType !== 'jpeg' && imageType !== 'jpg' && imageType !== 'png')
    throw 'image type must be jpeg, jpg or png';

  // Store License
  fs.rename(cnicbackendimage.path, imagePath, (errorRename) => {
    if (errorRename) {
      throw 'image store error';
    }
  });
    const updatedbackendimage = await Customer.findAndUpload(
    { _id: newbackendimage._id },
    {
      cnicbackendUrl: `Customer/cnicbackendimage_${newbackendimage._id}${imageExtension}`,
    },
    
    { new: true },
  );
  
  return res.status(200).json({ success: true, message: updatedbackendimage});
  }) catch (error) {
    fs.unlinkSync(updatedbackendimage.path);
    console.log('catch');
    console.log(error);
    return res.status(400).json({success:false, message: error});
   } 
  });
module.exports = router;  

This is slightly better, but still inconsistent. I was able to more easily spot the issue, which I mentioned earlier which was the 2nd catch you applied.

Here’s the formatted code after running it thru prettier

router.post("/Customer/personalinfo", async (req, res) => {
  const formData = formidable({
    multiples: true,
    uploadDir: "./public/Customer/",
  });

  formData.parse(req, async (error, fields, files) => {
    const {
      firstname,
      lastname,
      middlename,
      fathername,
      spousename,
      gender,
      meritalstatus,
      dateofbirth,
      dateofissuance,
      dateofexpiry,
      organization,
      emailaddress,
      city,
      province,
      cnic,
      contactno,
    } = fields;

    const { cnicfrontendimage, cnicbackendimage } = files;

    if (
      !firstname ||
      !lastname ||
      !middlename ||
      !fathername ||
      !spousename ||
      !gender ||
      !meritalstatus ||
      !dateofbirth ||
      !dateofissuance ||
      !dateofexpiry ||
      !organization ||
      !emailaddress ||
      !cnicfrontendimage ||
      !cnicbackendimage ||
      !city ||
      !province ||
      !cnic ||
      !contactno
    ) {
      return res
        .status(400)
        .json({ success: false, message: "All fields are required." });
    }

    try {
      const newCustomer = await Customer.create({
        firstname,
        lastname,
        middlename,
        fathername,
        spousename,
        gender,
        meritalstatus,
        dateofbirth,
        dateofissuance,
        dateofexpiry,
        organization,
        emailaddress,
        city,
        province,
        cnic,
        cnicfrontendimage,
        cnicbackendimage,
        contactno,
      });

      // Extract extension, path and type of images for frontendurl
      const imageExtension = cnicfrontendimage.name.substr(
        cnicfrontendimage.name.lastIndexOf(".")
      );
      const imagePath =
        "./public/Customer/cnicfrontendimage_" +
        newCustomer._cnic +
        imageExtension;
      const imageType = cnicfrontendimage.type.split("/").pop();

      // Check license image type
      if (imageType !== "jpeg" && imageType !== "jpg" && imageType !== "png")
        throw "image type must be jpeg, jpg or png";

      // Store License
      fs.rename(cnicfrontendimage.path, imagePath, (errorRename) => {
        if (errorRename) {
          throw "image store error";
        }
      });
      const updatedfrontendimage = await Customer.findAndUpload(
        { _id: newfrontendimage._id },
        {
          cnicfrontendUrl: `Customer/cnicfrontendimage_${newfrontendimage._id}${imageExtension}`,
        },

        { new: true }
      );

      return res
        .status(200)
        .json({ success: true, message: updatedfrontendimage });
    } catch (error) {
      fs.unlinkSync(updatedfrontendimage.path);
      console.log("catch");
      console.log(error);
      return res.status(400).json({ success: false, message: error });
    }
  });

  // Extract extension, path and type of images for backendurl
  const imageExtension = cnicbackendimage.name.substr(
    cnicbackendimage.name.lastIndexOf(".")
  );
  const imagePath =
    "./public/Customer/cnicbackendimage_" + newCustomer._cnic + imageExtension;
  const imageType = cnicbackendimage.type.split("/").pop();

  // Check license image type
  if (imageType !== "jpeg" && imageType !== "jpg" && imageType !== "png")
    throw "image type must be jpeg, jpg or png";

  // Store License
  fs.rename(cnicbackendimage.path, imagePath, (errorRename) => {
    if (errorRename) {
      throw "image store error";
    }
  });
  const updatedbackendimage = await Customer.findAndUpload(
    { _id: newbackendimage._id },
    {
      cnicbackendUrl: `Customer/cnicbackendimage_${newbackendimage._id}${imageExtension}`,
    },
    { new: true }
  );
  return res.status(200).json({ success: true, message: updatedbackendimage });
});
module.exports = router;

So at this point the code is at least valid. :slight_smile:

@bradtaniguchi Thanks for the help but I’m still facing Type error while submitting a form.