Как загрузить изображения, используя Multer в Node.js вместе с express -validation? - PullRequest
0 голосов
/ 07 февраля 2020

Я получаю все ошибки express -подтверждения, даже если я правильно разместил все поля ввода при попытке добавить атрибут 'enctype = "multipart / form-data"' в элемент формы в my hbs файл для загрузки изображений с использованием мультера в node.js.

sell.hbs

<section class="my_account_area pt--80 pb--55 bg--white">
    <div class="container">
        <div class="row">
            <div class="col-lg-6 col-12">
                    <div class="my__account__wrapper">
                        {{# if success}}
                            <section class="success">
                                <h2>Form submitted!</h2>
                            </section>
                        {{else}}
                        {{# if errors}}
                            <div class="alert alert-danger">
                                <section class="errors">
                                    <ul>
                                        {{# each errors}}
                                            <li>{{ this.msg }}</li>
                                        {{/each}}
                                    </ul> 
                                </section>
                            </div>   
                         {{/if}}
                        <h3 class="account__title">Fill Up the Information of Book</h3>
                        <form action="/book_upload" method="post" enctype="multipart/form-data">
                            <div class="account__form">
                                <div class="input__box">
                                    <label>Your Name <span>*</span></label>
                                    <input type="text" id="name" name="name">
                                </div>
                                <div class="input__box">
                                    <label>Phone No. <span>*</span></label>
                                    <input type="number" id="phone" name="phone">
                                </div>
                                <div class="input__box">
                                    <label>Name of book <span>*</span></label>
                                    <input type="text" id="book_name" name="book_name">
                                </div>
                                <div class="input__box">
                                    <label>Image Path <span>*</span></label>
                                    <input type="text" id="image_path" name="image_path">
                                </div>
                                <div class="input__box">
                                    <label>Price of Book<span>*</span></label>
                                    <input type="number" id="price" name="price">
                                </div>
                                <div class="input__box">
                                    <label>Description of Book<span>*</span></label>
                                    <input type="text" id="description" name="description" placeholder="e.g. To study in 1st year 1st part">
                                </div>
                                <div class="input__box">
                                    <label>Faculty<span>*</span></label>
                                    <input type="text" id="faculty" name="faculty">
                                </div>
                                <div class="form__btn">
                                    <button type="submit">Upload</button>
                                </div>
                            </div>
                        </form>
                    </div>
                    {{/if}}
                </div>
        </div>
    </div>
</section>

Вот как выглядит ошибка Express-validation errors

Но когда я удаляю express -validation , все работает нормально. Итак, мой вопрос, как я могу сохранить оба атрибута "enctype =" multipart / form-data "и express -validation? Здесь z мой маршрут. js file

Route. js

router.post('/book_upload', isLoggedIn, (req, res, next) => {
    req.check('name')
     .isLength({min:3}).withMessage('Name must be of 3 characters long.')
     .matches(/^[A-Za-z\s]+$/).withMessage('Name must be alphabetic.');
    req.check('phone')
     .isLength({min:10,max:10}).withMessage('Phone number must be of 10 digits.');
    req.check('book_name')
     .isLength({min:3}).withMessage('Book Name must be of 3 characters long.')
     .matches(/^[A-Za-z\s]+$/).withMessage('Book Name must be alphabetic.');
    req.check('price')
     .isNumeric().withMessage('Price must be numeric.');
    req.check('description')
     .isLength({min:3}).withMessage('Description must be of 3 characters long.')
     .matches(/^[<A-Za-z0-9></A-Za-z0-9>\s]+$/).withMessage('Please write appropriate description.')
    req.check('faculty')
     .isLength({min:3}).withMessage('Faculty must be of 3 characters long.')
     .matches(/^[A-Za-z\s]+$/).withMessage('Faculty must be alphabetic.')

    var errors = req.validationErrors();
    if (errors){
        req.session.errors = errors;
        req.session.success = false;
    } else {
        req.session.success = true;

        var item = {
            name: req.body.name,
            phone: req.body.phone,
            book_name: req.body.book_name,
            image_path: req.body.image_path,
            price: req.body.price,
            description: req.body.description,
            faculty: req.body.faculty
        };
       var data = new Product(item);
       data.save();
    }
    res.redirect('/sell');
})
...