Node.js 无法读取未定义的multer的路径
请注意,我正在使用multer和nodejs提交图像,但每当我在没有选择任何文件的情况下单击提交按钮时,我会得到“无法读取未定义的路径”,但当选择文件时,错误不会弹出。但我想检查是否没有选择express validator不提供的文件Node.js 无法读取未定义的multer的路径,node.js,multer,Node.js,Multer,请注意,我正在使用multer和nodejs提交图像,但每当我在没有选择任何文件的情况下单击提交按钮时,我会得到“无法读取未定义的路径”,但当选择文件时,错误不会弹出。但我想检查是否没有选择express validator不提供的文件 `app.post("/ashanti",upload.single("pic"),function(req,res){ const pic=req.file.path; if(req.file){ console.log(req.file); } co
`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();
}`
错误正是它所说的,您正试图从
未定义的读取路径
你可以这样想:
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;
....
....
....
}
请在问题中输入代码,否则我们将无法帮助您。谢谢。在您的帮助下,我终于解决了这个问题。无论何时在项目中工作,我都将永远记住这一点