First install multer node package
then create upload.js as
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, callback) {
if (file.fieldname == "profilePic") {
callback(null, './uploads/profilePic/');
} else if (file.fieldname == "resume") {
callback(null, './uploads/resume/');
} else {
callback(null, './uploads/other/');
}
},
filename: function (req, file, callback) {
callback(null, Date.now() + '_' + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
if (file.fieldname == "profilePic") {
if ((file.mimetype).includes('jpeg') || (file.mimetype).includes('png') || (file.mimetype).includes('jpg')) {
cb(null, true);
} else {
cb(null, false);
}
}
if (file.fieldname == "resume") {
if ((file.mimetype).includes('doc') || (file.mimetype).includes('openxmlformats')) {
cb(null, true);
} else {
cb(null, false);
}
}
};
var upload = multer({ storage: storage, fileFilter: fileFilter, limits: { fileSize: 1 * 1024 * 1024 } })
module.exports = {
upload: upload
}
create user model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var uniqueValidator = require('mongoose-unique-validator');
const bcrypt = require("bcrypt");
var jwt = require('jsonwebtoken');
var secret = process.env.SECRET_KEY
require('../utils/database')
var UserSchema = new mongoose.Schema({
username: { type: String, lowercase: true, required: [true, "can't be blank"], match: [/^[a-zA-Z0-9]+$/, 'is invalid'], index: true },
email: { type: String, lowercase: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true },
firstName: String,
lastName: String,
password: String,
profilePic: String,
resume: String,
profilePics: [{
type: String
}]
}, {
timestamps: true
});
UserSchema.methods.setPassword = async function (password) {
this.password = await bcrypt.hash(password, bcrypt.genSaltSync(8))
return this;
};
UserSchema.methods.validPassword = async function (password) {
return await bcrypt.compare(password, this.password)
};
UserSchema.plugin(uniqueValidator, { message: 'is already taken.' });
UserSchema.statics.findByUserName = function (username, cb) {
return this.find({ username: username }, cb);
};
UserSchema.methods.generateJWT = function () {
var today = new Date();
var exp = new Date(today);
exp.setDate(today.getDate() + 60);
return jwt.sign({
id: this._id,
username: this.username,
exp: parseInt(exp.getTime() / 1000),
}, secret);
};
UserSchema.methods.toAuthJSON = function () {
return {
username: this.username,
email: this.email,
token: this.generateJWT(),
firstName: this.firstName,
lastName: this.lastName
};
};
var User = mongoose.model('User', UserSchema);
module.exports = {
"User": User,
"UserSchema": UserSchema
}
create routes/users.js
var express = require('express');
var router = express.Router();
var User = require('../models/User').User;
const { model } = require('mongoose')
var { upload } = require('../utils/upload')
//single input type file field
router.post('/signin', upload.single('profilePic'), async function (req, res, next) {
var user = new User({
username: req.body.username,
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
profilePic: req.file.filename
});
var usernameTaken = await User.findByUserName(req.body.username)
if (usernameTaken.length == 0) {
console.log("Hashing password")
var newUser = await user.setPassword(req.body.password)
var result = await newUser.save()
res.json({ "msg": "saved", data: result })
} else {
res.json({ "msg": "username already taken" })
}
});
//two input type file fields
router.post('/signin/twofilefield', upload.fields([{ name: 'resume', maxCount: 1 }, { name: 'profilePic', maxCount: 10 }]), async function (req, res, next) {
//profilePic
var profilePics = []
req.files["profilePic"].forEach((fl) => {
profilePics.push(fl.filename)
})
//resume
var resume = req.files["resume"][0].filename
var user = new User({
username: req.body.username,
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
profilePics: profilePics,
resume: resume
});
var usernameTaken = await User.findByUserName(req.body.username)
if (usernameTaken.length == 0) {
console.log("Hashing password")
var newUser = await user.setPassword(req.body.password)
var result = await newUser.save()
res.json({ "msg": "saved", data: result })
} else {
res.json({ "msg": "username already taken" })
}
});
//multiple files uploaded against single input type file
router.post('/signin/multiupload', upload.array('profilePic', 10), async function (req, res, next) {
var profilePics = []
req.files.forEach((fl) => {
profilePics.push(fl.filename)
})
var user = new User({
username: req.body.username,
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
profilePic: profilePics[0],
profilePics: profilePics
});
var usernameTaken = await User.findByUserName(req.body.username)
if (usernameTaken.length == 0) {
console.log("Hashing password")
var newUser = await user.setPassword(req.body.password)
var result = await newUser.save()
res.json({ "msg": "saved", data: result })
} else {
res.json({ "msg": "username already taken" })
}
});
module.exports = router;
Complete code can be obtained at
https://github.com/gitsangramdesai/mongoose-multer-express
No comments:
Post a Comment