Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

file still uploads with multer even after failed form validation

I have a form for adding a product which lets a user input product name, description etc. and also allows an image upload.

In my app.js file which is my entry point, I have:

const fileStorage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, 'uploads');
    },
    filename: (req, file, cb) => {
       cb(null, new Date().toISOString() + '-' + file.originalname);
    }
  });


  const fileFilter = (req, file, cb) => {
    if (
      file.mimetype === 'image/png' ||
      file.mimetype === 'image/jpg' ||
      file.mimetype === 'image/jpeg'
    ) {
      cb(null, true);
    } else {
      cb(null, false);
    }
  };

app.use(multer({ storage: fileStorage , fileFilter: fileFilter, limits: { fileSize: 100000} }).single('image'));

Open in new window


Here is my controller:

exports.postAddListing = (req, res, next) => {
    const title = req.body.title;
    const category = req.body.category;
    const description = req.body.description;
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(422).render('account/add-listing', {
            pageTitle: 'Add Item',
            path: '/account/add-listing',
            errorMessage: errors.array(),
            successMessage: null,
            oldInput: {
                title: title,
                description: description
            }
        });
    }

    const image = req.file;
    const imageUrl = image.path;

    const product = new Product({
        title: title,
        category: category,
        description: description,
        userId: req.user,
        datePosted: Date.now(),
        imageUrl: imageUrl
    });
    product.save()
    .then(result => {
        const successMessage = req.flash('success', 'Item sucessfully added');
        res.redirect('/account/add-listing');
    })
    .catch(err => console.log(err));
};

Open in new window


I am using express-validator for form validation. The problem I have is that if I for example leave all fields empty but choose an image, validation will fire and I will get error messages but the image will still upload. If form validation fails I don't want the image to upload but not sure how to achieve that.
ASKER CERTIFIED SOLUTION
Avatar of Zakaria Acharki
Zakaria Acharki
Flag of Morocco image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Crazy Horse

ASKER

Not really sure what you mean. This is my route:

router.post('/add-listing',
 [
    body('title', 'Item name required.')
    .not().isEmpty()
    .escape(),
    body('category', 'Category required')
    .not().isEmpty(),
    body('description', 'Description required.')
    .not().isEmpty(),
    body('image', 'image upload error')
    .custom((value, {req}) => {
       if (!req.file) {
         throw new Error('Valid image required.');
       }
       return true;
    })
 ],
 isAuth, accountController.postAddListing);

Open in new window


isAuth just checks that the user is logged in before calling the controller.