Search code examples
javascriptnode.jsformsexpressmulter

How to submit form with Multer with optional file submission?


I'm using multer for submitting form in my express app. The problem is the form has optional image submission option. That means a user can add photo if s/he wants, but s/he can submit the form without image as well. There is no problem with image submission. But multer is not submitting the form when there is no image, even not the other fields.

const express = require('express');
const router = express.Router();
const Company = require('../controller/CompanyController');
const multer  = require('multer');
const path = require('path');

let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/images/logos');
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

let upload = multer({ storage: storage }).any();

router.route('/companies').post(upload, Company.Create);

module.exports = router;

Solution

  • One workaround of this is to check the value of req.file once your submission goes through. If you do not provide a file in your form, req.file should have the value of undefined. However, if you submit a file it should be an object. Therefore, you could write a simple if statement like so:

    function Create() {
      if (req.file !== undefined) {
      // process image here
      }
      // process all other fields
    }
    

    Hope it helps!