Skip to content

Commit 3c7ce1e

Browse files
Krishna KantKrishna Kant
Krishna Kant
authored and
Krishna Kant
committed
Using Multer upload a File
1 parent 4cb9f02 commit 3c7ce1e

File tree

8 files changed

+185
-7
lines changed

8 files changed

+185
-7
lines changed

controllers/postsController.js

+1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ module.exports.create = async (req, res)=> {
3232
module.exports.destroy = async (req, res)=> {
3333
try {
3434
let post = await Post.findById(req.params.id);
35+
// console.log(post.user);
3536

3637
if(post.user == req.user.id) {
3738
post.deleteOne();

controllers/usersController.js

+37-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
const User = require('../models/user');
2+
const fs = require('fs');
3+
const path = require('path');
24

35
module.exports.profile = async (req, res)=> {
46
try {
@@ -15,9 +17,38 @@ module.exports.profile = async (req, res)=> {
1517

1618
module.exports.update = async (req, res)=> {
1719
if(req.user.id == req.params.id) {
18-
let user = await User.findById(req.params.id, req.body);
19-
req.flash('success', 'Profile Updated!')
20-
return res.redirect('back');
20+
try {
21+
let user = await User.findById(req.params.id);
22+
23+
User.uploadedAvatar(req, res, function(err) {
24+
if(err) {
25+
console.log('Multer Error: ', err); return;
26+
}
27+
28+
user.name = req.body.name;
29+
user.email = req.body.email;
30+
31+
if(req.file) {
32+
33+
if(user.avatar) {
34+
const curAvatarPath = path.join(__dirname, '..', user.avatar);
35+
if(fs.existsSync(curAvatarPath)) {
36+
fs.unlinkSync(curAvatarPath);
37+
}
38+
}
39+
40+
// this is saving the path of the uploaded file into the avatar field in the user
41+
user.avatar = User.avatarPath + '/' + req.file.filename;
42+
}
43+
44+
user.save();
45+
req.flash('success', 'Profile Updated!👍')
46+
return res.redirect('back');
47+
});
48+
} catch (err) {
49+
req.flash('error', err);
50+
return res.redirect('back');
51+
}
2152
} else {
2253
req.flash('error', 'Unauthorized!');
2354
return res.status(401).send("Unathorized");
@@ -50,7 +81,7 @@ module.exports.signUp = (req, res)=> {
5081
module.exports.create = async (req, res)=> {
5182
try {
5283
if (req.body.password != req.body.confirm_password) {
53-
req.flash('error', `Passwords doesn't not match`);
84+
req.flash('error', `Passwords doesn't not match😭`);
5485
return res.redirect('back');
5586
}
5687

@@ -71,7 +102,7 @@ module.exports.create = async (req, res)=> {
71102

72103
// For Creating Session and Cookies Store In Browser
73104
module.exports.createSession = async (req, res)=> {
74-
req.flash('success', 'Logged in Successfully!');
105+
req.flash('success', 'Logged in Successfully!👍');
75106
return res.redirect('/');
76107
}
77108

@@ -83,7 +114,7 @@ module.exports.destroySession = (req, res) => {
83114
console.log('Error in killing Session!')
84115
return;
85116
}
86-
req.flash('success', 'You have logged out!');
117+
req.flash('success', 'You have logged out!😝');
87118
return res.redirect('/');
88119
});
89120
}

index.js

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ app.use(expressLayout);
3131
app.use(cookieParser());
3232

3333
app.use(express.static("./assets"));
34+
app.use('/uploads', express.static(__dirname + '/uploads'));
3435

3536
app.set("view engine", "ejs");
3637
app.set("views", "views");

models/user.js

+22
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
const mongoose = require('mongoose');
22

3+
const multer = require('multer');
4+
const path = require('path');
5+
const AVATAR_PATH = path.join('/uploads/users/avatars');
6+
37
const userSchema = new mongoose.Schema({
48
email: {
59
type: String,
@@ -13,11 +17,29 @@ const userSchema = new mongoose.Schema({
1317
name : {
1418
type: String,
1519
require: true
20+
},
21+
avatar: {
22+
type: String
1623
}
1724
}, {
1825
timestamps: true
1926
});
2027

28+
29+
let storage = multer.diskStorage({
30+
destination: function(req, file, cb) {
31+
cb(null, path.join(__dirname, '..', AVATAR_PATH));
32+
},
33+
filename: function(req, file, cb) {
34+
cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname));
35+
}
36+
});
37+
38+
39+
// Static
40+
userSchema.statics.uploadedAvatar = multer({storage : storage}).single('avatar');
41+
userSchema.statics.avatarPath = AVATAR_PATH;
42+
2143
const User = mongoose.model('User', userSchema);
2244

2345
module.exports = User;

package-lock.json

+120
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
"express-ejs-layouts": "^2.5.1",
2020
"express-session": "^1.17.3",
2121
"mongoose": "^7.3.1",
22+
"multer": "^1.4.5-lts.1",
2223
"node-sass-middleware": "^1.0.1",
2324
"nodemon": "^2.0.22",
2425
"passport": "^0.6.0",
1.58 MB
Loading

views/user_profile.ejs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
<link rel="stylesheet" href="/css/user_profile.css" />
2+
<img src="<%= user.avatar %>" alt="<%= user.name %>" width="100">
23

34
<% if(user.id == profile_user.id) { %>
45
<!-- if user matches then show the form -->
5-
<form action="/users/update/<%= profile_user.id %>" method="POST">
6+
<form action="/users/update/<%= profile_user.id %>" method="POST" enctype="multipart/form-data">
67
<input
78
type="text"
89
name="name"
@@ -17,6 +18,7 @@
1718
value="<%= profile_user.email %>"
1819
required
1920
/>
21+
<input type="file" name="avatar" placeholder="Profile Picture">
2022
<input type="submit" value="Update" />
2123
</form>
2224
<%}else { %>

0 commit comments

Comments
 (0)