I have a problem uploading an image file to my server, I watched a tutorial on YouTube about multer and I do exactly the same thing that is done in the tutorial and for whatever reason I get an error: (“TypeError: Cannot read property ‘path’ of undefined”). I googled for the error and found some people having the same issue and I tried to solve it like them, but it didn’t work for me.
This is my code:
JavaScript
x
31
31
1
const multer = require('multer');
2
3
const storage = multer.diskStorage({
4
destination: function(req, file, cb) {
5
cb(null, './public/images/profilePictures');
6
},
7
filename: function(req, file, cb) {
8
cb(null, new Date().toISOString() + file.originalname);
9
}
10
});
11
12
const fileFilter = (req, file, cb) => {
13
// reject a file
14
if (file.mimetype === 'image/jpg' || file.mimetype === 'image/png') {
15
cb(null, true);
16
} else {
17
cb(null, false);
18
}
19
};
20
21
const upload = multer({
22
storage: storage,
23
limits: {
24
fileSize: 1024 * 1024 * 5
25
},
26
fileFilter: fileFilter
27
});
28
29
app.use(express.static('public'))
30
31
the Image Schema and model:
JavaScript
1
6
1
const imageSchema = new mongoose.Schema({
2
profilePicture: String
3
})
4
5
const Image = new mongoose.model('Image', imageSchema)
6
My post route:
JavaScript
1
8
1
app.post('/changeProfilePic', upload.single('profilePicture'), function(req, res, next){
2
console.log(req.file);
3
const newImage = new Image({
4
profilePicture: req.file.path
5
})
6
newImage.save()
7
})
8
My html upload form:
JavaScript
1
5
1
<form action="/changeProfilePic" method="POST" enctype = "multipart/form-data">
2
<input type="file" name="profilePicture" placeholder="Image" />
3
<button class="btn btn-light btn-lg" type="submit">Upload</button>
4
</form>
5
and when I logged the value of (req.file) it says that its type is ‘undefined’, so that must mean that multer didn’t recognize or even didn’t received the image file. what am I doing wrong that multer doesn’t get the file?
Advertisement
Answer
I changed the destination to ./uploads
works fine for me