我已将文件上传添加到用户注册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;
我已修复了我的问题,我已将其添加到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");
}
};