multer中间件未被调用

时间:2018-05-30 11:11:20

标签: node.js multer

我想使用multer上传图片,我不知道为什么根本没有调用upload.single(),下面是带有存储和过滤器设置的multer配置。

var multer = require('multer');

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads/');
  },
  filename: function(req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  // reject a file
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: fileFilter
});

这是调用multer中间件的路径。

router.post('/addnew',auth.isLoggedIn,upload.single('photo'),(req,res,next)=>{
  // console.log("name:",req.body.title,req.body.descp,req.body.price,req.body.imagePath );

  console.log('file:',req.files," & ",req.file);


}

使用文件输入和按钮进行表格控制。

<form action="/product/addnew"  method="post">
     <div class="form-group row">
         <label><input type="file" id="photo" name="photo" class="form-control"/></label>
       </div>

     <div class="form-group row">
         <button type="submit" class="btn btn-primary">Add Product</button>
     </div>
</form>

1 个答案:

答案 0 :(得分:0)

如果您需要解决方案,则可以使用此--

var multer = require('multer');

var storage = multer.diskStorage({

    destination : function(req,file,cb){
        cb(null,'./uploads');
    },
    filename : function(req,file,cb){
        cb(null,file.originalname);
    }   
});

var filefilter = function(req,file,cb){ 

         if(file.originalname.match(/\.(png|jpeg|jpg)$/))
            {
            return cb(null,true);     
            }
        else{
             return  cb(new Error(('in image only image is allowed')));
            }

}    
var upload = multer({storage : storage,limits : {
    filesize :1024*1024*5
    },fileFilter :filefilter
});

module.exports = upload; 

router.post('/addnew',auth.isLoggedIn,upload.single('photo'),(req,res,next)=>{
  // console.log("name:",req.body.title,req.body.descp,req.body.price,req.body.imagePath );

  console.log('file:',req.files," & ",req.file);


}