【问题标题】:How to solve "can not read property path of undefined" in node.js(Multer)如何解决node.js(Multer)中“无法读取未定义的属性路径”
【发布时间】:2020-12-08 21:13:56
【问题描述】:

我想使用 multer 将图像上传到 mongodb。这是我的代码:

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./uploads");
  },
  filename: function (req, file, cb) {
    cb(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});

const upload = multer({
  storage: storage,
});

mongoClient 内部:

client.connect((err) => {
const adminTasks = client
    .db(`${process.env.DB_NAME}`)
    .collection("adminTasks");

app.post("/uploadImage", upload.single("myImage"), (req, res) => {
    const img = fs.readFileSync(req.file.path);
    const encode_image = img.toString(base64);

    // defining json obj for image
    const final_image = {
      contentType: req.file.mimetype,
      path: req.file.path,
      image: new Buffer(encode_image, "base64"),
    };

    // inserting image to db
    userTasks.insertOne(final_image, (err, result) => {
      console.log(result);
      if (err) {
        console.log(err);
      }
      console.log("saved to db");
      res.contentType(final_image.contentType);
      res.send(final_image.image);
    });
  });
});

错误是:

TypeError: Cannot read property 'path' of undefined

我已经阅读了很多关于由于 enctype="multipart/form-data" 导致问题发生的问题。但我用过这个:

<form action="http://localhost:5000/uploadImage" method="POST">
          <input type="file" enctype="multipart/form-data" name="myImage" />
          <input type="submit" value="upload Image" />
        </form>

如何解决这个问题????

【问题讨论】:

标签: node.js mongodb express multer


【解决方案1】:

对于upload.single(),文件名在req.file。那是一个代表文件名的字符串。没有属性req.file.path。所以,你应该使用req.file 来获取文件名。

【讨论】:

  • 使用req.file,新的错误是----> TypeError [ERR_INVALID_ARG_TYPE]:“path”参数必须是字符串类型或者是Buffer或URL的实例。收到未定义
  • @Fuad9 - console.log(typeof req.file) 显示什么?
  • 错误显示为 --> const img = fs.readFileSync(req.file);在 Object.openSync (fs.js:450:10) 在 Object.readFileSync (fs.js:360:35) 并且 req.file 的类型显示未定义
  • @Fuad9 - 好的,如果typeof req.file 显示undefined, then you have an upstream problem with multer. Perhaps your const storage = ...` 部分错误。我对 multer 的了解还不够,无法帮助您。
【解决方案2】:

file.fieldname 可能未定义。这就是完整路径变得不确定的原因。

相反,请尝试查看 req.file 的名称。这对我有用:

filename: (req, file, cb) => {
    cb(null, file.originalname)
}

文档以一般方式错误地指出存储配置应包含

filename: (req, file, cb) => {
    cb(null, file.fieldname)
}

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 2021-03-24
    • 2018-07-22
    • 2018-02-26
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2021-05-10
    相关资源
    最近更新 更多