当我的文件图像超过1MB时,我试图向邮递员res.status.send
发送错误提示消息。但是,当我尝试运行代码时,它只会给我这整个错误消息。我只想获取错误消息本身(LIMIT_FILE_SIZE)。有什么方法可以实现?
IMAGE HERE
我当前的app.js:
var multer = require('multer');
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads');
},
filename: function(req, file, callback) {
callback(null, path.basename(file.originalname));
}
})
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) {
return callback(null, false, new MulterError('LIMIT_FILE_SIZE'))
}
callback(null,true)
}
});
app.post("/upload",upload.single('name'),(req,res,next) => {
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})
}
}
})
答案 0 :(得分:2)
Multer将错误委托给Express,这是在express中抛出错误的标准方法。要捕获特定错误,可以在路由回调中使用multer上传中间件。这是multer的documentation提供的方法,@ Mattia Rasulo也提到了该方法
router.post('/image', function (req, res, next) {
upload.single('image')(req, res, function (error) {
if (req.fileValidationError) {
res.status(500).send({ message: req.fileValidationError });
}
else {
if (error) {
res.status(500).send({ message: error.code === 'LIMIT_FILE_SIZE' ? "Image more than 1MB!" : error.message });
}
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})
}
}
});
});
答案 1 :(得分:1)
Multer只是将错误发送到全局错误中间件,因此您只需捕获该错误并检查是什么错误:
if(err.message === 'file too large') [change the message as you need].
这就是我处理您完全相同的问题的方式!