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

时间:2019-05-21 17:26:27

标签: node.js express multer

我将表单与文件上载和常规表单字段混合在一起,并且在将此表单发送到Node.js服务器时,我正在验证表单,但是问题是我不知道如何停止(例如)其中一种表单上载文件字段为空。 例如:

if(name.trim().length < 1){
   //stop uploading of file
   return res.status(409).send({
     message: 'provide name'
   })
 }

我该怎么做(Multer和ExpressJS)?

2 个答案:

答案 0 :(得分:1)

在我的情况下(节点和快递),我正在使用以下代码。

从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");
       }
}

答案 1 :(得分:0)

您可以简单地抛出错误:

快递:

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

这是您可以做的事情,或者您可以返回其他内容而不是抛出错误。