如何使用其他字段验证来停止在Multer中上传文件?

时间:2018-09-01 16:27:10

标签: node.js express multer

我已将文件上传添加到用户注册API,它可以正常工作,但是我有问题。 如果用户输入数据库中已经存在的电子邮件,则我为电子邮件添加了验证,API会给出错误信息并拒绝将数据插入数据库。 但是我找不到一种为文件提供相同功能并停止上传的方法 API:

const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const multer = require("multer");

// multer config
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, "./static/uploads/avatars");
  },
  filename: function(req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  }
});
const fileFilter = (req, file, cb) => {
  if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
    cb(null, true);
  } else {
    cb("please upload only image");
  }
};
const upload = multer({
  storage: storage,
  limits: 1024 * 1024 * 20,
  fileFilter: fileFilter
}).single("avatar");

// Load User model
const User = require("../../models/User");

// @route   GET api/users/test
// @desc    Tests users route
// @access  Public
router.get("/test", (req, res) => res.json({ msg: "Users Works" }));

// @route   GET api/users/register
// @desc    Register user
// @access  Public
router.post("/register", (req, res) => {
  upload(req, res, function(err) {
    if (err) {
      return res.status(400).json({ avatar: "please upload picture" });
    }
    User.findOne({ email: req.body.email })
      .then(user => {
        if (user) {
          return res.status(400).json({ email: "email already exist" });
        } else {
          // Everything went fine
          const newUser = new User({
            name: req.body.name,
            email: req.body.email,
            avatar: req.file.path,
            password: req.body.password
          });

          bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(newUser.password, salt, (err, hash) => {
              if (err) throw err;
              newUser.password = hash;
              newUser
                .save()
                .then(user => res.json(user))
                .catch(err => console.log(err));
            });
          });
          //
        }
      })
      .catch(err => console.log(err));
  });
});

module.exports = router;

1 个答案:

答案 0 :(得分:0)

我已解决问题,已将其添加到fileFilter中:

const fileFilter = (req, file, cb) => {
  // checking file type
  if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
    cb(null, true);
  } else {
    cb("please upload only image");
  }
  //check if the email is not exist
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      cb("this user already exist");
    }
  });

  // validation
  const { errors, isValid } = validateRegisterInput(req.body);

  // Check Validation
  if (!isValid) {
    cb("is not valid");
  }
};