首页 > 解决方案 > 类型错误:无法读取未定义的属性“文件名”--multer

问题描述

对于这个社区贡献者,我有一个非常相似的问题。我如何在我的邮递员中生成 multer 错误消息我按照其他用户的评论进行操作,并且成功了!但是,当我尝试发布小于 1MB 并且是 jpg 格式的图像(我在编辑之前设法做到这一点)时,它现在失败并声明TypeError: Cannot read property 'filename' of undefined

我的 app.js 代码:

const upload = multer({
    dest: storage,
    storage: storage,
    limits: {
      fileSize: 1024 * 1024
    },
    fileFilter: function(req, file, callback,error) {
        var ext = path.extname(file.originalname);
        var error_msg = error instanceof multer.MulterError;
        if(ext !== '.jpg') {
             req.fileValidationError = "Not a jpg file!";
             return callback(null, false, req.fileValidationError);
        }
        if(error_msg) {
            req.fileSizeError = "Image more than"
            return callback(null, false, req.fileSizeError)
        }
        callback(null,true)
    }
  });

app.post("/upload", function (req, res, next) {
    upload.single('name')(req, res, function (error) {
        if(req.fileValidationError) {
            res.status(500).send({message:req.fileValidationError});
        }
        else {
            if(error.code === 'LIMIT_FILE_SIZE') {
                req.fileSizeError = "Image more than 1MB!";
                res.status(500).send({message:req.fileSizeError});
            }
            else {
                console.log('File Received!');
                console.log(req.file);
                var sql = "INSERT INTO `file`(name,description,type,size) VALUES('" + req.file.filename + "', '" + (req.file.encoding + "_" + req.file.destination + "_" + req.file.path)+ "', '" + req.file.mimetype + "', '" + req.file.size + "')";
                db.query(sql, (error, results) => {
                    console.log('Inserted Data!');
                });
            const message = "Successfully Uploaded!"
            res.status(200).send({message:message, file_details:req.file})
            }
        }
    })
})

标签: mysqlnode.jsexpresserror-handlingmulter

解决方案


看起来错误处理不正确,尤其是在文件保存期间;未处理由此产生的错误。例如,尝试删除目标目录“uploads”然后上传文件,TypeError: Cannot read property 'filename' of undefined会再次抛出!

要解决此问题并确定究竟是什么错误,您应该处理upload.single()错误回调。

app.post("/upload", function (req, res, next) {
  upload.single('name')(req, res, function (error) {
    if (error) {
      console.log(`upload.single error: ${error}`);
      return res.sendStatus(500);
    }
    // code
  })
});

推荐阅读