I’ve tried so many time to upload file using multer but I always get this error:
TypeError: Cannot read properties of undefined (reading ‘0’)
I uploaded file previously with the same code. Can anyone tell me why?
multer.middleware.js
:
import multer from 'multer';
import path from 'path';
const storage = multer.diskStorage({
destination: (req, file, cb) => {
return cb(null, 'public');
},
filename: (req, file, cb) => {
let ext = path.extname(file.originalname);
console.log(ext);
return cb(null, Date.now()+ext);
}
});
const fileFilter = (req, file, cb) => {
if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png'){
cb(null, true);
}else{
cb(null, false);
}
}
const upload = multer({
storage: storage,
fileFilter: fileFilter
});
export {upload};
controller.js
:
import {Employee} from './employee.model.js';
import { uploadCloudinary } from './cloudinary.js';
//Add employee
const addEmployee = async (req, res) => {
const { name, email, phone, dob } = req.body;
if ([name, email, phone, dob].some(field => field?.trim() === '')) {
return res.status(400).json({ message: 'All fields are required' });
}
const isExist = await Employee.findOne({ $or:[{email},{phone}] });
if(isExist) {
console.log("User with email or phone already exist! Try new one..");
return res.status(409).json({ message: 'User with email or phone already exist! Try new one..' });
}
const imagePath = req.files?.avatar[0]?.path;
if (!imagePath) return res.status(400).json({ message: 'Avatar is required and path!' });
const avatar = await uploadCloudinary(imagePath);
if (!avatar) return res.status(400).json({ message: 'Avatar is required!' });
const employee = await Employee.create({
name,
email,
phone,
dob,
avatar: avatar?.url || '',
});
};
export default { addEmployee};
router.js
:
import { Router } from "express";
import controller from "./employee.controller.js";
import {upload} from './multe.middileware.js'
const router = Router();
router.route("/add").post(
upload.fields([{
name: 'avatar', maxCount: 1,
}]) ,controller.addEmployee);
export default router;
NB: I try to fix it by changing
const imagePath = req.files?.avatar[0]?.path;
to
const imagePath = req.files?.avatar?.path;
In this case, the TypeError is gone but file isn’t uploaded. I get a message “Avatar path is required”.
My question is since the code ran properly earlier, why is it causing an error now?
Naim Islam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.