TypeError: Cannot read property 'filename' of undefined--multer

TypeError: Cannot read property 'filename' of undefined--multer

对于这位社区贡献者,我有一个非常相似的问题。 我跟进了其他网友的评论,成功了!但是,当我尝试 post 一张小于 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})
            }
        }
    })
})

看起来错误处理不对,尤其是在文件保存过程中;其中产生的错误没有得到处理。例如尝试删除目标目录"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
  })
});

确保发送请求 header "Content-Type": "multipart/form-data"

数组只包含对象,不包含文件名属性。数组中的第一个对象确实具有文件名 属性。 Select 其中第一个也是唯一一个使用 req.files['image'][0].filenamereq.files[0].filename 的项目,它应该可以工作。