File and Text not uploading at a time on body-parser and multer?

I have a from to upload text and a image at a time. I am using multer and body-parser. but when I give enctype="multipart/form-data"to form req.body not getting any value.

<form method="post" action="/admin/dashbord/product" enctype="multipart/formdata">

<div class="form-group">
     <label for="source">Title</label>
       <input type="text" name="title" class="form-control" id="source" value="{{product.title}}" placeholder="Enter Title">
 </div>


 <div class="form-group">
    <label for="source">Image</label>
     <input type="file" name="image" class="form-control" id="source" placeholder="Enter Title">
 </div>

 <button type="submit" class="btn btn-primary">Submit</button>
 </form>

Router:

 router.post('/product', function (req, res) {
       var filename;
       upload(req, res, (err) => {
         filename = req.file.filename

    })

      const product = {
        title: req.body.title,
            image: filename,
      };

       console.log(product)
    })

Multer Uploading code:

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

// Init Upload

const upload = multer({
    storage: storage,
    limits:{fileSize: 1000000},
    fileFilter: function(req, file, cb){
      checkFileType(file, cb);
    }
  }).single('image');

  // Check File Type
  function checkFileType(file, cb){
    // Allowed ext
    const filetypes = /jpeg|jpg|png|gif/;
    // Check ext
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    // Check mime
    const mimetype = filetypes.test(file.mimetype);

    if(mimetype && extname){
      return cb(null,true);
    } else {
      cb('Error: Images Only!');
    }
  }

if I poat without enctype body parser is working well.otherwise getting undefined.

if I console imagename into upload function working well outside getting undefined.

1 answer

  • answered 2018-10-09 19:45 mad max

    write this all in your upload function:

     upload(req, res, (err) => {
          filename = req.file.filename;
          const product = {
            title: req.body.title,
            image: filename,
          };
    
           console.log(product)
    })
    

    it is very simple you have just missed it up.