【问题标题】:multer npm: TypeError: Cannot read property 'path' of undefinedmulter npm:TypeError:无法读取未定义的属性“路径”
【发布时间】:2021-03-24 00:22:20
【问题描述】:

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

这是我的代码:

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)

我的发帖路线:

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) 的值时,它说它的类型是“未定义”,所以这一定意味着 multer 没有识别甚至没有收到图像文件。 multer没有得到文件我做错了什么?

【问题讨论】:

  • 您好,= 周围有多余的空格,请登录enctype = "multipart/form-data",尝试更改为enctype="multipart/form-data"
  • 您给文件的文件名可能有问题,导致 multer 失败并且没有将文件属性附加到请求对象。 Linux 和 Windows 都不支持带有冒号的文件名,这是由 new Date().toISOString() 产生的。
  • @Vitalii 你好,我改了还是不行。
  • @JimNilsson。我删除了新的 ``` Date().toISOString() ``` 仍然 multer 无法识别 req.file
  • 您是否也确定了目录./public/images/profilePictures 存在,并且路径正确?

标签: javascript node.js express mongoose multer


【解决方案1】:

我将目的地更改为./uploads 对我来说很好

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 2015-11-22
    • 2014-08-16
    • 1970-01-01
    相关资源
    最近更新 更多