Setup image upload

This commit is contained in:
Ethanell 2020-04-26 18:56:38 +02:00
parent 356f25ef33
commit 7d4460b46e
3 changed files with 22 additions and 1 deletions

1
.gitignore vendored
View file

@ -4,4 +4,5 @@ package-lock.json
# Image Node data
users.json
images/

21
app.js
View file

@ -5,8 +5,21 @@ let bodyParser = require('body-parser');
let session = require("express-session");
let fs = require("fs");
let passwordHash = require('password-hash');
let multer = require("multer");
let crypto = require("crypto");
let path = require("path");
let app = express();
let storage = multer.diskStorage({
destination: './images/',
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
if (err) return cb(err)
cb(null, raw.toString('hex') + path.extname(file.originalname))
})
}}
);
let upload = multer({storage: storage});
if (!fs.existsSync("users.json")) {
fs.writeFileSync("users.json", "{}");
@ -43,7 +56,7 @@ function isAuth(req, res, next) {
app.use(morgan("dev"))
.use(express.static("public"))
.use(bodyParser.urlencoded({ extended: true }))
.use(cookieParser())
.use(cookieParser(process.env.SECRET))
.use(session({
secret: process.env.SECRET,
resave: false,
@ -55,6 +68,12 @@ app.use(morgan("dev"))
.get("/", isAuth, (req, res) => {
res.render("index");
})
.post("/upload", isAuth, upload.single("image"), (req, res) => {
if (req.body.image) {
fs.writeFile("images/", data, options, callback)
}
res.redirect("/");
})
.get("/login", (req, res) => {
let fail = false;
if ("fail" in req.query) {

View file

@ -9,6 +9,7 @@
"express": "^4.17.1",
"express-session": "^1.17.1",
"morgan": "^1.10.0",
"multer": "^1.4.2",
"password-hash": "^1.2.2",
"pug": "^2.0.4"
},