使用Multer验证和上传2个图像和文本字段

时间:2019-05-13 13:46:22

标签: node.js express multer express-validator

我有一个产品表单,其中包含两个图像字段和其他文本字段,我将第一个图像字段命名为“ Featured”,另一个命名为“ seconded”。该功能是用户首先看到的,用户可以单击以查看第二张图像。

我正在使用multer上传图像。我遵循了文档https://www.npmjs.com/package/multer。我还使用“ express-validator”来验证和清理字段。我之前曾使用multer制作单张图片。但是我无法使它正常工作。我已经尽力了。我得到的只是一些正在上传的号码。

routes / admin.js

var express = require('express');
var router = express.Router();
var adminControllers = require('../controllers/adminControllers');
const { check } = require('express-validator/check');
const multer = require('multer'); 
const multerConfig = multer({ dest: '../functions/imagesStorage' });

router.get('/addproduct', adminControllers.addProductPage);

//Get the image fields
var productImageUpload = multerConfig.fields([ {  name: 'featured'}, {  name: 'second'}]);

router.post('/addproduct', [ 
  check('name').not().isEmpty().trim().escape(),
  check('category').not().isEmpty().trim().escape(),
  check('description').not().isEmpty().trim().escape(),
  check('featured').not().isEmpty(),
  check('second').not().isEmpty(),
  check('price').not().isEmpty().trim().escape(),
  check('quantity').not().isEmpty().trim().escape(),
  check('weight').not().isEmpty().trim().escape()
], productImageUpload, adminControllers.addProduct);

module.exports = router;

controllers / adminControllers.js

const knex = require('../db/knex');
var slug = require('slug');
const { check, validationResult } = require('express-validator/check');

   //POST PRODUCTS TO DB category
exports.addProduct = function(req, res, next)
{
     var errors = validationResult(req);

    if(!errors.isEmpty()){
          req.session.errors = errors;
          req.session.success = false;
          console.log('express-validator', errors);
          return res.redirect('/admin/addproduct');
      }

    req.session.success = true;

          var url = slug(req.body.name);
          var Adminuser = "bob"; 

          knex('products').insert({
               product_name: req.body.name,
               product_category: req.body.category,
               description: req.body.description,
               //get the file name and store in db
               image: req.files.originalname,
               second_image: req.files.originalname,
               price: req.body.price,
               quantity: req.body.quantity,
               weight: req.body.weight,
               url: url,
               users: Adminuser
          }).then(()=>{
              console.log(req.file.featured.originalname);
            res.render('administration/admin');

          })
}

functions / imagesStorage.js

const multer = require('multer'); 


const multerConfig = {
    storage: multer.diskStorage({
      //setup where the user's file will go
      destination: function(req, file, next){
        next(null, 'images/products');
      },
      //then give the file a unique name here
      filename: function(reg, file, next){
        console.log(file);
        const ext = file.mimetype.split('/')[1];
        //next(null, file.originalname + '-' + Date.now() + '.'+ext)
        //next(null, Date.now() + '-' + file.originalname)
        next(null, file.originalname)
      }
    }),
    //a means of ensuring only images are uploaded.
    fileFilter: function(req, file, next){
      if(!file){
        next();
      }
      const image = file.mimetype.startsWith('image/');
      if(image){

        console.log('photo uploaded ');
        next(null, true);
      }else{
        console.log('file not supported');

        return next();
      }
    }
  }

  module.exports = multerConfig;

addproducts.hbs

   <div class="modal-body">
            <form action="addproduct" enctype="multipart/form-data" method="post">

                    <p>Please fill the form to add products </p>

                    <div class="form-group">
                        <label>Product Name</label>
                        <input type="text" aria-label="Page Title" name="name" id="name" placeholder="Add Product Name" class="form-control">
                    </div>

                    <div class="form-group">
                      <label>Select Product Category </label>
                    <select name="category" class="custom-select" id="category" aria-label="Select Category">
                        <option selected>Choose...</option>
                        <option value="1">One</option>
                        <option value="2">Two</option>
                        <option value="3">Three</option>
                    </select>

                    <div class="form-group">
                        <label>Product Description</label>
                        <textarea class="form-control" name="description" id="description" placeholder="Add text" name="editor" rows="3"></textarea>
                    </div>



                      <div class="form-group">
                            <label>Product feature Image</label>
                            <label for="exampleFormControlFile1">Example file input</label>
                            <input type="file" name="featured" class="form-control-file" id="exampleFormControlFile1">
                      </div>

                         <div class="form-group">
                            <label>Product Second Image</label>
                            <label for="exampleFormControlFile1">Example file input</label>
                            <input type="file" name="second" class="form-control-file" id="exampleFormControlFile1">
                      </div>


                    <div class="form-group">
                        <label>Products Price</label>
                        <input type="number" aria-label="Page Title" name="price" id="price" placeholder="Add Meta Tag" class="form-control">
                    </div>

                    <div class="form-group">
                        <label>Quantity</label>
                        <input type="number" name="quantity" aria-label="Quantity" id="quantity" placeholder="Add Quantity" class="form-control">
                    </div>

                    <div class="form-group">
                        <label>Weight</label>
                        <input type="number" name="weight" aria-label="Weight" id="Weight" placeholder="Add weight" class="form-control">
                    </div>

                </div>

        <button type="submit" class="btn btn-primary">Add Product</button>
        <a class="btn btn-primary btn-group text-white"  id="productbtn" href="/admin">Go To Admin</a>



      </form>
       </div> 

0 个答案:

没有答案