【问题标题】:How can I continue handling a request in Express.js if there is no Image detected by Multer?如果 Multer 没有检测到图像,我如何继续处理 Express.js 中的请求?
【发布时间】:2017-08-17 01:30:36
【问题描述】:

在我使用 Multer 的 Express 应用程序中,我想接收可能包含或不包含文件的表单数据,然后对其进行处理。此表单数据包含其他数据,例如,我想添加到数据库中的名称是否附有图像

app.js (Node / Express / Multer)

app.post
(
    '/create_item', 
    multer({dest : 'temp/'}).single('image'), 
    function(req, res, next)
    {
        // I want to do stuff here with the req.body, 
        // even if there wasn't a file attached for Multer to process.
        // As of now, it just shuts down the request when there is no file.

        // When there is an image attached there is no problem.
    }
)

因此,如果没有附加文件,Multer 似乎不允许继续请求。即使没有附加图像供 Multer 使用,是否有办法继续在服务器上执行操作?

我做了很多研究和思考以找到解决方案,但遗憾的是找不到。如果您能帮助我,将不胜感激!

【问题讨论】:

  • 也许您只需要更新您的 multer 版本。我在我的电脑上运行了你的代码,它工作正常。或者,在下面使用我的答案。
  • 您在此评论中可能是对的,尽管我的版本运行良好。我发现这只发生在我从特定页面(客户端)发送请求时。它可能“只是”该 javascript 页面中的一些杂乱变量干扰表单数据:服务器端/Multer 很好。谢谢,我教过也许 Multer 不可能。

标签: javascript node.js express post multer


【解决方案1】:

可能有点丑陋的解决方法,但试试这个。创建我们自己的中间件来检测文件是否被传递。如果有文件通过,则使用 mutter,否则,绕过它。

app.post
(
    '/create_item', 
    function(req, res, next) {
        req.rawBody.indexOf('filename=') === -1 ? next() : multer({dest : 'temp/'}).single('image')(req, res, next);
    }, 
    function(req, res, next)
    {
        // I want to do stuff here with the req.body, 
        // even if there wasn't a file attached for Multer to process.
        // As of now, it just shuts down the request when there is no file.

        // When there is an image attached there is no problem.
    }
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 2011-07-13
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多