Multer - Stop File Uploading If Form Validation Fails

▼魔方 西西 提交于 2019-12-13 03:07:58

问题


i have mixed form with file upload and normal form fields, and while sending this form to Nodejs server i am validating form but problem is that i do not know how to stop uploading the file if (for example) one of the form field is empty. so for example:

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

how can i do that (Multer & ExpressJS)?


回答1:


I was using following code in my case (node & express).

From routes.js file I am calling this insertRating method. like below

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



回答2:


You can simply throw error:

in express::

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

this is something you can do or you can return something else instead of throwing an error.



来源:https://stackoverflow.com/questions/56243533/multer-stop-file-uploading-if-form-validation-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!