Multiple file uploads in nodejs using express-fileupload?

2.8k views Asked by At

Currently I am able to post this to mongodb. It works fine.

PROBLEM Instead of one attachment, I should be able to post many attachments independent of each other, there will be N different buttons available for the N uploads.

const form = (req, res, next) => {

  const file = req.files.photo;

  file.name = `photo_${Math.random(0, 10012)}-${Math.random(0, 2000)}${
    path.parse(file.name).ext
  }`;

  file.mv(`./public/uploads/${file.name}`, async (err) => {
    if (err) {
      console.error(err);
      return res.status(500).json({
        message: `Problem With File Upload`,
      });
    }
    
    const upload = await Form.create({
       approved: req.body.approved,
       email_: req.body.email,

       formData: {
        name: "req.body.formData.claimantName",
        nationality: "req.body.formData.claimantNationality",
        address: "req.body.formData.claimantAddress",
        email: "req.body.formData.claimantEmail",
      }, 

      fileOne: file.name1,
          
      // these are the next 
      // fileTwo: req.body.formData.name2,
      // fileThree: req.body.formData.name3,

    });
    return res.status(200).json({
      success: true,
      message: `File Uploaded Successfully`,
      path: file.name,
    });
  });
};

router.route("/add").post(form);

I tried moving const upload = await Form.create(...) outside the file.mv(...) block and do somthing like this``` const file1 = req.files.photo1;

file1.name = photo_${Math.random(0, 10012)}-${Math.random(0, 2000)}${ path.parse(file1.name).ext };

It doesn't work properly.
1

There are 1 answers

0
Mohammad Basit On

I think you can fetch the uploaded files in the request object in your node server on the endpoint which receives the request in req.files object.

Your endpoint should catch files like this

const uploads = Object.values(req.files);

As you're going to get an object of key value pairs as key will be file name value will be file data object containing name etc. Object.values will convert that object to an array of objects having the information of uploaded files. After that create a promise that will catch the files like shown below:

Function to handle file uploads

handleFileUpload = (uploads) => {
   return new Promise((resolve, reject) => {
     const dbData = [];
     uploads.forEach(async (upload) => {
       const name = await `photo_${Math.random(0, 10012)}-${Math.random(0, 2000
       )}${path.parse(upload.name).ext}`;
       dbData.push(name);
       await upload.mv(`your-path/${name}`, async (err) => {
        if (err) {
          reject("Something wrong");
        }
      });
   });
  resolve(dbData);
 });
};

After that pass in the uploads to the promise and make a db insertion in the then block.

handleFileUpload(uploads).then((response) => { ... }).catch((e) => { ... });

The response will have all the image paths.

Note : I'm considering the files to be IMAGES