gpt4 book ai didi

mysql - 我如何在我的 postman 中产生多个错误消息

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:24 25 4
gpt4 key购买 nike

当我的文件图像超过 1MB 时,我正在尝试res.status.send 向 postman 发送一条错误消息。但是当我尝试运行我的代码时,它只会给我整 block 错误消息。我只想获取错误消息本身(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})
}
}
})


最佳答案

Multer 将错误委托(delegate)给 Express,这是 express 中抛出错误的标准方式。要捕获特定错误,您可以在路由回调中使用 multer upload 中间件。这是 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})
}
}
});
});

关于mysql - 我如何在我的 postman 中产生多个错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59526207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com