Multer access req.body without uploading files

巧了我就是萌 提交于 2019-12-11 06:07:25

问题


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:


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,
  });
});


来源:https://stackoverflow.com/questions/41170918/multer-access-req-body-without-uploading-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!