Home > Software engineering >  express-fileupload requires me to upload a file which is optional on the form
express-fileupload requires me to upload a file which is optional on the form

Time:05-19

I have a challenge with express-fileupload when a user doesn't upload a file that is meant to be optional. Someone should please help me out.

This is my code:

const file = req.files.document;
  const file2 = req.files.document2;
  const uploader = req.body.fullname;
  

  const filename = `CV_${uploader}_${file.name}`;
  const filename2 = `Cover_${uploader}_${file2.name}`;
  
  let savedFile = filename.replace(/\s /g, "");
  let savedFile2 = filename2.replace(/\s /g, "");
  const path = "uploads/"   savedFile;
  const path2 = "uploads/"   savedFile2;

  file.mv(path, (err) => {
    if (err) {
      console.log(err);
    }
  });

  file2.mv(path2, (err) => {
    if (err) {
      console.log(err);
    }
  });

The second file is optional for the user to upload. When the user doesn't upload it, it shows an error. Please, how can I make it optional from here.

It shows an error like this: Type Error: Cannot read property 'name' of undefined

Thank you so much.

CodePudding user response:

I did not fully understand. But I want to say something.

I think your frontend code is like this;

<form >
  <input type="file" name="document" />
  <input type="file" name="document2" />
</form>

This code block is probably the cause of that error.

const filename2 = `Cover_${uploader}_${file2.name}`;

Because user doesn't upload second file and document2 is probably undefined or null.

You can use this if the file named document2 is optional.

const file = req.files.document;
const file2 = req.files.document2;

const uploader = req.body.fullname;
  

const filename = `CV_${uploader}_${file.name}`;
let savedFile = filename.replace(/\s /g, "");
const path = "uploads/"   savedFile;


file.mv(path, (err) => {
    if (err) {
      console.log(err);
    }
 });

if (file2 && file2.name) {
  const filename2 = `Cover_${uploader}_${file2.name}`;
  let savedFile2 = filename2.replace(/\s /g, "");
  const path2 = "uploads/"   savedFile2;

  file2.mv(path2, (err) => {
    if (err) {
      console.log(err);
    }
  });
}

CodePudding user response:

So, I was able to find my way around the whole thing.

I did it like this...

app.post("/form", (req, res) => {

  const file = req.files.document;
  const file2 = req.files.document2;
  const uploader = req.body.fullname;

  const filename = `CV_${uploader}_${file.name}`;
  let savedFile = filename.replace(/\s /g, "");
  const path = "uploads/"   savedFile;

  file.mv(path, (err) => {
    if (err) {
      console.log(err);
    }
  });

  // function to save file2 to server if it exists and send the filename to be used outside the function

  const filename2 = file2 ? `Cover_${uploader}_${file2.name}` : null;
  let savedFile2 = filename2 ? filename2.replace(/\s /g, "") : null;
  const path2 = filename2 ? "uploads/"   savedFile2 : null;


  if (file2 && file2.name) {
    const filename2 = `Cover_${uploader}_${file2.name}`;
    let savedFile2 = filename2.replace(/\s /g, "");
    const path2 = "uploads/"   savedFile2;

    file2.mv(path2, (err) => {
      if (err) {
        console.log(err);
      }
    });
  }

  // Saving to the database...
  const date = new Date();
  const dateNow = moment(date).format("llll");

  const job = new Jobs({
    position: req.body.positions,
    language: req.body.lang,
    fullName: req.body.fullname,
    gender: req.body.gender,
    education: req.body.education,
    email: req.body.email,
    address: req.body.address,
    phone: req.body.phone,
    fileCV: savedFile,
    fileCover: savedFile2,
    date: dateNow,
  });

  job.save((err) => {
    if (!err) {
      res.render("success");
    }
  });

  // Sending to mail server

  const output = `
<p> You have a new applicant! </p>
<h2> Contact Details </h2>
<ul>
    <li>position: ${req.body.positions}</li>
    <li>language: ${req.body.lang} </li>
    <li>fullName: ${req.body.fullname}</li>
    <li>gender: ${req.body.gender}</li>
    <li>email: ${req.body.email}</li>
    <li>address: ${req.body.address}</li>
    <li>phone: ${req.body.phone}</li>
    <li>education: ${req.body.education}</li>
</ul>
    `;

  const transporter = nodemailer.createTransport({
    service: "localhost",
    port: 1025,
    secure: false, // true for 465, false for other ports
    auth: {
      user: "project.1", // generated ethereal user
      pass: "secret.1", // generated ethereal password
    },
    tls: {
      rejectUnauthorized: false,
    },
  });

  let senderName = req.body.fullname;
  let senderEmail = req.body.email;
  //send mail with unicode symbols
  let mailOptions = {
    from: `"${senderName}" <${senderEmail}>`, // sender address
    to: "[email protected], [email protected]", // list of receivers
    subject: "Job Application ✔", // Subject line
    text: "Check out my details here...", // plain text body
    html: output, // html body
    attachments: [
      { filename: `${savedFile}`, path: `${path}` },
      { filename: `${savedFile2}`, path: `${path2}` },
    ], // list of attachments
  };

  // sending mail with defined transport object
  transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
      console.log(err);
    } else {
      console.log("Message sent: %s", info.messageId);
      //   console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
    }
  });
  
});
  • Related