mysql - 类型错误:无法读取未定义的属性“文件名”--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})
}
}
})
})
解决方案
看起来错误处理不正确,尤其是在文件保存期间;未处理由此产生的错误。例如,尝试删除目标目录“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
})
});
推荐阅读
- ubuntu - Google Compute Engine VM 上的 Ubuntu do-release-upgrade
- c# - C#只查询xslt的父节点
- python-3.x - ModuleNotFoundError:没有名为“settings_sensitive”的模块
- firebase - Firebase Cloud Functions 与 Firebase 移动原生 SDK
- docker - docker容器启动后是否可以增加内存限制?
- python - 网页上更快的 SQL 结果(Python 3.6、Flask、Pymssql)
- javascript - 使用 path.centroid() 找不到路径对象的中心
- python-3.x - python web开发的前置步骤?
- javascript - 在javascript中出现“预期未定义”错误
- php - 没有通过 Google_Service_YouTube 进行直播(google/apiclient)