node.js - 如何在 multer 中将 cb 错误转换为 json 格式

标签 node.js nodes multer

我正在使用 multerNodeJS 中编写图片上传代码

我的代码是

var upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 5
    },
    fileFilter: (req, file, cb) => {
        if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
            cb(null, true);
        } else {
            return cb(JSON.stringify({ "success": false, "message": "invalid mime type" }), false);

        }
    }
});

router.post('/upload', upload.single('image'), (req, res, next) => {
    const io = req.app.get('io');
    const product = new db.product({
        name: req.body.name,
        category: req.body.category,
        image: req.protocol + "://" + req.hostname + ":" + req.socket.localPort + "/img/roundtshirt/" + req.file.filename
    });
});

当我从 Postman 上传无效文件时,我收到以下错误,例如我的回调

<pre>{&quot;success&quot;:false,&quot;message&quot;:&quot;invalid mime type&quot;}</pre>

但是,我想将该错误转换为正确的 json 格式。

我尝试返回 json 但出现错误。

最佳答案

您可以使用 自定义错误处理 来自 Multer here

这是我的例子:

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 5
    },
    fileFilter: (req, file, cb) => {
        if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
            cb(null, true);
        } else {
            return cb(new Error('Invalid mime type'));
        }
    }
});

const uploadSingleImage = upload.single('image');

app.post('/upload', function (req, res) {

    uploadSingleImage(req, res, function (err) {

        if (err) {
            return res.status(400).send({ message: err.message })
        }

        // Everything went fine.
        const file = req.file;
        res.status(200).send({
            filename: file.filename,
            mimetype: file.mimetype,
            originalname: file.originalname,
            size: file.size,
            fieldname: file.fieldname
        })
    })
})

完整示例代码,请访问https://gist.github.com/huynhsamha/348722d47ee457454688698ff77fee1a

感谢阅读:D

关于node.js - 如何在 multer 中将 cb 错误转换为 json 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60725016/

相关文章:

javascript - 我如何让 'get' 被自动调用?

javascript - 当 Sequelize 查询是一个 promise 时,为什么我需要一个 promise ?

javascript - setGame 的问题

javascript - 使用node js按名称过滤

Node.js 类型错误 : Cannot read property 'file' of undefined

node.js - 从 mongodb 检索图像数据并在浏览器上显示

node.js - Nodejs Express - 如何在 package.json 中设置 max-old-space-size?

javascript - 可变变量可以从闭包中访问

Java 使用 LinkedList 的节点

c++ - 链表 - 指针