Skip to content
Advertisement

multer npm: TypeError: Cannot read property ‘path’ of undefined

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:

const multer = require('multer');

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './public/images/profilePictures');
  },
  filename: function(req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  // reject a file
  if (file.mimetype === 'image/jpg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: fileFilter
});

app.use(express.static('public'))

the Image Schema and model:

const imageSchema = new mongoose.Schema({
    profilePicture: String
})

const Image = new mongoose.model('Image', imageSchema)

My post route:

app.post('/changeProfilePic', upload.single('profilePicture'), function(req, res, next){
    console.log(req.file);
   const newImage = new Image({
       profilePicture: req.file.path
   })
   newImage.save()
})

My html upload form:

<form action="/changeProfilePic" method="POST" enctype = "multipart/form-data">
      <input type="file" name="profilePicture" placeholder="Image" />
      <button class="btn btn-light btn-lg" type="submit">Upload</button>
    </form>

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement