无法读取未定义 multer 的路径

cannot read path of undefined multer

PLease I am using multer and nodejs to submit an image but whenever I click on the submit button without any file selected I get"cannot read path of undefined" but when a file is selected the error dont pop up.但我想检查是否没有选择 express-validator 不提供的文件

`app.post("/ashanti",upload.single("pic"),function(req,res){
 const pic=req.file.path;

if(req.file){
console.log(req.file);

}
 const newuser=new user(

     {  pic:pic

      })

    newuser.save().then(function(err,user){
        if(err) throw err

          })
             })

 And this is the multer setup

const storage=multer.diskStorage({
 destination:function(req,file,cb){
      cb(null,"images/ashantiimg");
  },
 filename:function(req,file,cb){
  cb( null , file.fieldname+"-"+Date.now()+file.originalname);
  }


  })
  const filefilter=function(req,file,cb){




   if(file.mimetype==="image/png"||file.mimetype==="image/jpeg"||
 file.mimetype==="image/jpg"){
  cb(null,true)
  }

   else{
      cb(null,false)

   }

   }

const upload=multer({storage:storage,fileFilter:filefilter});

This is the pug file for the form 

 form#frm(method="post" action="/ashanti" enctype="multipart/form-data" )   
 .form-group
  label
   input.form-control.seven(type="file",name="pic") 
   input( type="button" onclick="subi()" value="post") 
   script.
    function subi(){
     const post=document.getElementById("frm");
     post.submit();
     post.reset();
     }`

错误如其所言,您正在尝试从 undefined

读取 path

你可以这样想:

const testObj = {path: 'my path'}
const path = testObj.path

这行得通吗?因为一切都已定义,但是如果您尝试这样做会发生什么:

let testObj; //you only defined the name of the variable, but it is undefined.
let path = testObj.path // can not read path from undefined.

所以基本上你需要做的是:

  • 确保变量已定义
  • 设置变量的默认值。

确保已定义:

app.post("/ashanti",upload.single("pic"),function(req,res){
 // if some of these entries are undefined, we return
 if(!req || !req.file || !req.file.path) return;
 const pic=req.file.path;
 ....
 ....
 ....
}

设置默认值:

app.post("/ashanti",upload.single("pic"),function(req,res){
 const { path: pic }= req.file || {}; // we are sure that we are reading from an object.
 if(!pic) return;
 ....
 ....
 ....
}