0

Iam using busboy body parser to parse the multipart form data. So Iam getting the fields like name, username key values in req.body and files in req.files. But Iam unable to upload files to the directory using multer.

app.use(busboyBodyParser());
app.post('/createUser', (req, res) => {

  console.log(req.body);
  console.log(req.files);
   const storage = multer.diskStorage({
     destination: './public/uploads/',
     filename: function (req, file, cb) {
       cb(null, file.fieldname + '-' + Date.now() + 
         path.extname(file.originalname));
     }
   });
   const upload = multer({
      storage: storage
   }).single(req.files['uploadpic']);
   upload(req, res, (err) => {
   });

});
Vipin
  • 153
  • 7
  • 21

1 Answers1

1

You don't need to use busboy with multer as it is built on top of it.

Your files are not being saved because your files come in an array form but you're trying to read it in as a single file also with a wrong syntax.

upload.single('fieldName') //is the syntax for single file

Your code will be rewritten like this:

//removing busbodyparser

//declaring multer configs 

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

const upload = multer({
   storage: storage
}).array('uploadpic', 8]

//make sure you define maxCount - here 8 is given as an example
//array will take in a number of files with the same 'uploadpic' field name

app.post('/createUser', (req, res) => {

    upload(req, res, function(err) {
        if (err) {
            //show error
        }

        //your files are saved and req.body and req.files are populated using multer

        console.log(req.files);
        console.log(req.body);
    });
});    
Asghar Musani
  • 568
  • 4
  • 20