I’m having trouble with file uploads using multer. When I try to access req.file in my route handler, it shows up as undefined and I get an error when trying to read its properties.
I followed a tutorial but something isn’t working right. Here’s what I have set up:
const multer = require('multer');
const diskStorage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads/avatars');
},
filename: function(req, file, callback) {
callback(null, Date.now() + '-' + file.originalname);
}
});
const filterFiles = (req, file, callback) => {
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
callback(null, true);
} else {
callback(null, false);
}
};
const fileUpload = multer({
storage: diskStorage,
limits: {
fileSize: 5 * 1024 * 1024
},
fileFilter: filterFiles
});
My database model:
const avatarSchema = new mongoose.Schema({
avatarPath: String
})
const Avatar = mongoose.model('Avatar', avatarSchema)
The route that handles uploads:
app.post('/upload-avatar', fileUpload.single('avatar'), function(req, res){
console.log(req.file); // this prints undefined
const newAvatar = new Avatar({
avatarPath: req.file.path // error happens here
})
newAvatar.save()
})
HTML form:
<form action="/upload-avatar" method="POST" enctype="multipart/form-data">
<input type="file" name="avatar" />
<button type="submit">Submit</button>
</form>
When I check req.file it’s always undefined. What could be causing multer to not process the uploaded file?