Add file type filter on upload

This commit is contained in:
Ethanell 2020-04-27 20:58:31 +02:00
parent 2f3df8dd28
commit 34c328214e
3 changed files with 22 additions and 3 deletions

View file

@ -3,7 +3,11 @@ let isAuth = require("../user").isAuth;
router.get("/", isAuth, (req, res) => {
res.render("index");
let invalidType = false;
if ("invalidType" in req.query) {
invalidType = true;
}
res.render("index", {invalidType: invalidType});
});

View file

@ -13,11 +13,24 @@ let storage = multer.diskStorage({
});
}
});
let upload = multer({storage: storage});
let upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (file.mimetype.substring(0, 6) !== "image/") {
req.fileErrorValidation = true;
return cb(null, false, new Error("Wrong file type"));
}
cb(null, true);
}
});
router.post("/", isAuth, upload.single("image"), (req, res) => {
res.redirect("/images/" + req.file.filename);
if (req.fileErrorValidation) {
res.redirect("/?invalidType");
} else {
res.redirect("/images/" + req.file.filename);
}
});

View file

@ -1,6 +1,8 @@
extend layout
block content
h1 Image Node
if invalidType
h2.fail Invalid image type !
form(method="POST", action="/upload", enctype="multipart/form-data")
input.file_button(type="file", name="image", accept="image/*")
button(type="submit") Upload