Multer access req.body without uploading files

2019-07-27 09:59发布

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.

1条回答
劳资没心,怎么记你
2楼-- · 2019-07-27 11:03

Try with multer's any() function:

var multer = require('multer');
var getFields = multer();
router.post('/add',getFields.any(),function(req,res){
  // any files, if sent, will be in req.files 
  var artist = new ArtistModel({
    name : req.body.name.toLowerCase(),
    description:req.body.description,
  });
});

If you are sure there will be no files submitted, use multer's none() function:

var multer = require('multer');
var getFields = multer();
router.post('/add',getFields.none(),function(req,res){
  // uploading files will cause an error
  var artist = new ArtistModel({
    name : req.body.name.toLowerCase(),
    description:req.body.description,
  });
});
查看更多
登录 后发表回答