multer npm: TypeError: Cannot read property 'path' of undefined

multer npm: TypeError: Cannot read property 'path' of undefined

我在将图像文件上传到我的服务器时遇到问题,我在 YouTube 上观看了一个关于 multer 的教程,我做了与教程中完全相同的事情,但无论出于何种原因,我收到了一个错误:("TypeError : 无法读取未定义的 属性 'path'")。我用谷歌搜索了这个错误,发现有些人有同样的问题,我试着像他们一样解决它,但它对我不起作用。

这是我的代码:

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'))

图像架构和模型:

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

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

我的post路线:

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

我的 html 上传表格:

<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>

当我记录 (req.file) 的值时,它说它的类型是 'undefined',所以这一定意味着 multer 没有识别甚至没有收到图像文件. multer 没有获取文件,我做错了什么?

我将目的地更改为 ./uploads 对我来说没问题