上传文件后获取路径报错: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 inreq.files(an array) instead ofreq.file(which is only for single-file uploads with.single()). - Wrong timing to fetch the path: You're trying to log
req.file.pathinside thefilenamecallback. 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 thefilenamecallback (this was the root of the undefined error). - Added the
upload(req, res, callback)execution block—this is where Multer finishes processing files, soreq.filesis fully populated with each file's path and metadata. - Used a loop on
req.filesto log each path, since you're handling up to 3 files with.array().
内容的提问来源于stack exchange,提问作者jdotdoe
相关产品推荐
相关产品推荐

