I have a form with some text fields and file inputs which cannot be empty, I want to do some operations with the text fields first(adding to database) and if these operations were successful then upload the files. This is my code right now :
var multer = require('multer');
var getFields = multer();
router.post('/add',getFields.array(),function(req,res){
var artist = new ArtistModel({
name : req.body.name.toLowerCase(),
description:req.body.description,
});
I then add artist to my DB and in the successful callback I want the files to be uploaded. The problem is however I can't simply use getFields.array() because I have file inputs and I get "Unexpected fields" error, and if I dont use .array() I wont be able to get the post request body. Is there anyway to get the form text fields with enctype="multipart/form-data" first and then upload the files?
Update #2 Thanks to Dave I was able to get the text fields without uploading files , I successfully added my artist to my database, however I couldn't figure out how to upload the files afterwards, I created a new variable in the callback function of my addToDb :
var storage = multer.diskStorage({
destination: function (req, file, cb) {
//cb(null, 'artistsMedia/drake/songs')
var dir = 'artistsMedia/' + req.body.name.toLowerCase()+ '/images';
mkdirp(dir,err => cb(err,dir))
},
filename: function (req, file, cb) {
cb(null, req.body.name.toLowerCase() +'-'+ file.fieldname +'-'+ Date.now() + path.extname(file.originalname)) //Appending extension
},
});
var upload = multer({
storage: storage,
limits :{fileSize :52428800}
}).fields([{name:'Logo',maxCount:1},{name:'artistHome',maxCount:1},{name:'otherImgs',maxCount:10}]);
however calling upload(req,res,err)
doesnt seem to work.