问题描述
我正在尝试验证图像上传,以确保用户实际上传了图像而不是其他任何文件。这是我在app.js中的自定义验证
const {checkSchema} = require('express-validator/check');
app.use(checkSchema({
customValidators: {
isImage: function (value,filename) {
var extension = (path.extname(filename)).toLowerCase();
switch (extenion) {
case ".jpg":
return ".jpg";
case ".png":
return ".png";
case ".jpeg":
return ".jpeg";
case "":
return ".jpg";
default:
return false;
}
}
}
}))
这是我进行验证的发布路线
router.post('/add-product',[
imageFile = typeof req.files["image"] !== "undefined" ? req.files["image"][0].filename : "",check("title","Title must have a value.").not().isEmpty(),check("desc","Description must have a value.").not().isEmpty(),check("price","Price must have a value.").not().isDecimal(),check("image","you must upload an image.").not().isImage(imageFile)
],function (req,res) {
var title = req.body.title;
var slug = slug = title.replace(/\#+/g,"-").toLowerCase();
var desc = req.body.desc;
var price = req.body.price;
var category = req.body.category;
const result = validationResult(req);
var errors = result.errors;
if (!result.isEmpty()) {
Category.find(function (err,categories) {
res.render("admin/add_product",{
errors: errors,title: title,desc: desc,price: price,categories: categories
})
})
}
这是我尝试对其进行测试后得到的错误
express-validator: a validator/sanitizer with name isImage does not exist
C:\Users\LayintonDev\Desktop\cartTutorial\routes\admin_products.js:57
imageFile = typeof req.files["image"] !== "undefined" ? req.files["image"][0].filename : "",^
ReferenceError:未定义req 在对象。 (C:\ Users \ LayintonDev \ Desktop \ cartTutorial \ routes \ admin_products.js:57:32)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)