You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

上传文件后获取路径报错:TypeError: Cannot read property 'path' of undefined

Fixing "Cannot read property 'path' of undefined" in Multer File Upload

Hey there! Let's break down why you're hitting this error and how to fix it.

What's Causing the Error?

There are two key issues in your code:

  • Mismatched file access property: You're using multer().array("imgUploader", 3) to handle multiple files, so Multer stores the uploaded files in req.files (an array) instead of req.file (which is only for single-file uploads with .single()).
  • Wrong timing to fetch the path: You're trying to log req.file.path inside the filename callback. At this point, the file hasn't been saved to disk yet—this callback only exists to generate the filename, so the full path property doesn't exist here. You need to wait until Multer finishes processing the upload to access the paths.

Corrected Code

Here's the adjusted code that properly fetches and logs your file paths:

router.post('/uploadFile', function(req, res, next) {
  if(req.method == "POST"){
    var accessToken = req.query["access_token"];
    var customerID = req.decoded.userID;

    var Storage = multer.diskStorage({
      destination: function(req, file, callback) {
        callback(null, "./public/images");
      },
      filename: function(req, file, callback) {
        // Only handle filename generation here
        callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
      }
    });

    var upload = multer({ storage: Storage }).array("imgUploader", 3);

    // Run the upload and access file paths in the completion callback
    upload(req, res, function(err) {
      if (err) {
        return res.status(500).json({ error: err.message });
      }
      // Now req.files is available—loop through it to get each file's path
      req.files.forEach(file => {
        console.log("Uploaded file path:", file.path);
      });
      res.status(200).json({ message: "Files uploaded successfully", uploadedFiles: req.files });
    });
  }
});

Key Fixes Explained:

  • Removed the console.log(req.file.path) from the filename callback (this was the root of the undefined error).
  • Added the upload(req, res, callback) execution block—this is where Multer finishes processing files, so req.files is fully populated with each file's path and metadata.
  • Used a loop on req.files to log each path, since you're handling up to 3 files with .array().

内容的提问来源于stack exchange,提问作者jdotdoe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:13:07