Node.js Multer-如果表单验证失败,则停止文件上载

Node.js Multer-如果表单验证失败,则停止文件上载,node.js,express,multer,Node.js,Express,Multer,我将表单与文件上传和普通表单字段混合在一起,在将此表单发送到Nodejs服务器时,我正在验证表单,但问题是,如果(例如)其中一个表单字段为空,我不知道如何停止上传文件。 例如: if(name.trim().length < 1){ //stop uploading of file return res.status(409).send({ message: 'provide name' }) } if(name.trim().length{ 试试{ if(

我将表单与文件上传和普通表单字段混合在一起,在将此表单发送到Nodejs服务器时,我正在验证表单,但问题是,如果(例如)其中一个表单字段为空,我不知道如何停止上传文件。 例如:

if(name.trim().length < 1){
   //stop uploading of file
   return res.status(409).send({
     message: 'provide name'
   })
 }
if(name.trim().length<1){
//停止上载文件
返回资源状态(409)。发送({
消息:“提供名称”
})
}

我该怎么做(Multer&ExpressJS)?

您可以简单地抛出错误:

以明示方式:

app.get("/upload-image", multterUpload.single("image"), (req, res, next)=>{
  try{ 
       if(name.trim().length < 1) {
         throw new Error("name length is not valid");
         //or
         return res.status(409).json({msg: "failed"});
       }
  // you all operation ....
   res.status(200).json({msg: "success"});
  }cathc(e=>{ 
   next(e) 
  });
})
app.get(“/upload image”,multterUpload.single(“image”),(请求,恢复,下一步)=>{
试试{
if(name.trim().length<1){
抛出新错误(“名称长度无效”);
//或
返回res.status(409.json)({msg:“failed”});
}
//你们都在做手术。。。。
res.status(200).json({msg:“success”});
}cathc(e=>{
下一(e)
});
})

这是您可以执行的操作,或者您可以返回其他操作,而不是抛出错误。

我在本例中使用了以下代码(node&express)

从routes.js文件中,我将此方法称为insertRating方法。如下

//routes.js
router.post('/common/insertrating',RatingService.insertRating);

//controller class
// storage & upload are configurations 

var storage = multer.diskStorage({
destination: function (req, file, cb) {

    var dateObj = new Date();
    var month = dateObj.getUTCMonth() + 1; //months from 1-12

    var year = dateObj.getUTCFullYear();
    console.log("month and yeare are " + month + " year " + year);
    var quarterMonth = "";
    var quarterYear = "";

    var dir_path = '../../uploads/' + year + '/' + quarterMonth;

    mkdirp(dir_path, function (err) {
        if (err) {
            console.log("error is cominggg insidee");
        }
        else {
            console.log("folder is createtd ")
        }
        cb(null, '../../uploads/' + year + '/' + quarterMonth)
    })

    console.log("incomingggg to destination");

},
filename: function (req, file, cb) {

    console.log("incoming to filename")
    cb(null, Date.now() + "_" + file.originalname);
},

});

var upload = multer({
storage: storage,
limits: {
    fileSize: 1048576 * 5
},
fileFilter: function (req, file, callback) {
    var ext = path.extname(file.originalname);
    ext = ext.toLowerCase();
    console.log("ext isss " + ext);

    if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg' && ext !== '.pdf' && ext !== '.txt'
        && ext !== '.doc' && ext !== '.docx' && ext !== '.xlsx' && ext !== '.xls'
    ) {
        return callback(new Error('Only specific extensions are allowed'))
    }
    callback(null, true)
}

}).array('files', 5);


 // calling below insertRating method from routes js file...

exports.insertRating = async function (req, res) {
        let quarterData = req.query.quarterData;
        quarterData = JSON.parse(quarterData);

        if (quarterData != null) { // here you can check your custom condition like name.trim().length
               req.files = []; // not required 
               upload(req, res, async function (err) { // calling upload 
                            if (err) {

                                res.send("error is cominggg")
                                return;
                            } else {
                                res.send("file is uploaded");
                      }

                            //
               });

        }
       else {
               res.send("filed must not be empty");
       }
}

但我需要向用户发送消息是的,您可以使用错误处理程序来完成;或者只使用::if(name.trim().length<1){return res.status(200).json({msg:“success”})}我想你没有理解我说的话,或者你是新来的Expressor,我应该使用插入作为中间件吗?我已经编辑了anwser。我正在从routes.js文件调用insertRating方法,我正在app.js中使用这个routes.js文件,比如(app.use(routes))你能告诉我我的答案有帮助吗?