image_node/routes/upload.js

39 lines
897 B
JavaScript
Raw Normal View History

2020-04-26 20:12:50 +02:00
let router = require("express").Router();
let isAuth = require("../user").isAuth;
let multer = require("multer");
let crypto = require("crypto");
let path = require("path");
let storage = multer.diskStorage({
destination: './images/',
filename: (req, file, cb) => {
crypto.pseudoRandomBytes(16, (err, raw) => {
if (err) return cb(err)
cb(null, raw.toString('hex') + path.extname(file.originalname));
});
}
});
2020-04-27 20:58:31 +02:00
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);
}
});
2020-04-26 20:12:50 +02:00
router.post("/", isAuth, upload.single("image"), (req, res) => {
2020-04-27 20:58:31 +02:00
if (req.fileErrorValidation) {
res.redirect("/?invalidType");
} else {
res.redirect("/images/" + req.file.filename);
}
2020-04-26 20:12:50 +02:00
});
module.exports = router;