Express-validator在使用Multer时不起作用

问题描述

我知道这个问题已经问过很多次了,但是我没有找到解决问题的方法。我搜索了很多东西,但不幸的是没有成功!!

我正在Express中构建一个带有文件上传,文本框和textarea输入的表单。所有3个字段均为必填项。我正在使用Multer处理文件上传,并使用express-validator进行表单字段验证。我的图像上传正常,但表单字段未得到验证。如果我将文本框和textarea保留为空并上传图片,则不会出现表单验证错误,也不会上传图片!以下是我的代码:

image.js控制器

var multer = require('multer'); 
const { validationResult } = require('express-validator');
module.exports = {
   create(req,response) {
        const saveImage = function(){

            var storage = multer.diskStorage({
                destination: function (req,file,cb) {
                    cb(null,'./public/upload')
                },filename: function (req,cb) {
                    const possible = 'abcdefghijklmnopqrstuvwxyz0123456789';
                    const possbile_len = possible.length;
                    var imgUrl = '';
                    for (let i = 0; i < 10; i += 1)
                    {
                        imgUrl += possible.charAt(Math.floor(Math.random() * possbile_len));
                    }
                    var ext = path.extname(file.originalname).toLowerCase();                    
                    cb(null,imgUrl+'_'+Date.now()+ext);
                }
            });

            const fileFilter = (req,cz) => {
                if(!file)
                {
                    req.fileValidationError = 'Please upload an image file';
                    return cz(new Error("Please upload an image file"),false);
                }

                var ext = path.extname(file.originalname).toLowerCase();
                if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif')
                {
                    // BELOW CHECK WILL NOT WORK PROPERLY IN CURRENT VERSION OF MULTER AS IT CHECKS THE MIME TYPE FROM HEADER
                    // SEND BY BROWSER WHICH CAN BE SPOOKED. THIS ISSUE IS RESOLVED IN VER. 2.X WHICH IS IN ALPHA STAGE
                    if (file.mimetype === "image/png" || file.mimetype === "image/jpg" || file.mimetype === "image/jpeg" || file.mimetype === "image/gif")
                    {
                        cz(null,true);
                    }
                    else
                    {
                        req.fileValidationError = 'Only image files are allowed!';
                        return cz(new Error("Only image files are allowed!"),false); // if validation failed then generate error
                    }
                }
                else
                {
                    req.fileValidationError = 'Only image files are allowed!';
                    return cz(new Error("Only image files are allowed!"),false); // if validation failed then generate error
                } 
            };

            var uploads = multer({
                storage: storage,limits : {fileSize : 1000000},// fileSize is in bytes. 1MB
                fileFilter: fileFilter
            }).single('usrpic');  
            
            uploads(req,response,function (err) { 
                
                if (req.fileValidationError)
                {   
                    // File upload validation failed                    
                    req.session.sessionFlash = {
                        type: 'error',message: req.fileValidationError
                    }
                    response.redirect('/images');                
                }
                else if (err)
                {
                    // Some error occurred when uploading                    
                    req.session.sessionFlash = {
                        type: 'error',message: err.message
                    }
                    response.redirect('/images');
                }
                else
                {             
                    // BELOW LINES PRINTS FORM VALUES,IF ENTERED
                    console.log('--------------------req--------------');
                    console.log('title ',req.body.title);
                    console.log('description',req.body.description);

                    const errors = validationResult(req.body);
                    console.log('---------------errors--------------');
                    console.log(errors); // HERE errors IS BLANK EVEN IF I SUBMIT EMPTY FORM FIELDS

                    if (!errors.isEmpty()) // An error occurred
                    {
                        var arrTemp = errors.array();
                        var arrErrors = {};
                        arrTemp.forEach(function(err) {
                            arrErrors[err.param] = err.msg;
                        }); 

                        req.session.sessionFlash = {
                            type: 'error',message: arrErrors
                        }

                        response.redirect('/images');
                    }
                    else
                    {
                        // CREATE A RECORD IN MONGODB
                        response.send('success');
                    }
                }
            });  
        }

        if(! req.session.loggedin)
        {
            return response.redirect('/login');
        }
        
        saveImage();    // CALL THE FUNCTION
   }
}

validator.js帮助器

const { check } = require('express-validator');

exports.uploadImage = [
    check('title','Title is required').not().isEmpty(),check('description','Description is required').not().isEmpty()        
];

routes.js

const express = require('express'),router = express.Router(),home = require('../controllers/home'),image = require('../controllers/image'),usrCtrl = require('../controllers/userCtrl'),validator = require('../helpers/validator');
    
module.exports = (app)=>{
    router.get('/',home.index);
    router.get('/images',image.index);
    router.get('/images/:image_id',image.show);
    router.post('/images',validator.uploadImage,image.create);
    router.post('/images/:image_id/like',image.like);
    router.post('/images/:image_id/comment',image.comment);
    router.get('/login',usrCtrl.login);
    router.post('/login',validator.loginUser,usrCtrl.loginProcess);
    router.get('/register',usrCtrl.register);
    router.post('/register',validator.registerUser,usrCtrl.registerProcess);
    app.use(router);
};

为解决即使表单验证失败也上传图片的情况,我认为如果表单验证失败则需要删除上传的图片。

有人可以帮助我解决这个问题吗?

非常感谢, 熟透了

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...