You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Multer实现文件上传时出现TypeError: next is not a function错误求助

问题分析与解决方案

错误原因

你遇到的TypeError: next is not a function是因为:

  • uploadFile是Multer生成的Express中间件函数,它必须接收req, res, next三个参数,但你在file_upload方法里只传了前两个,导致Multer内部调用next(err)时找不到该函数。
  • 同时Multer的中间件基于回调实现,并非Promise,直接用await无法正确等待上传流程完成。

解决方案(两种可选)

方法一:将uploadFile作为路由中间件使用(推荐,符合Express/Multer设计规范)

修改你的路由配置,把uploadFile直接作为路由的中间件,而非在控制器内手动调用:

  1. 路由文件示例
const express = require('express');
const router = express.Router();
const controller = require('./你的控制器文件路径');
// 这里直接使用你定义好的uploadFile
const uploadFile = require('./你的Multer配置文件路径').uploadFile;

// 把uploadFile放在控制器方法前面,作为路由中间件
router.post('/upload/:number', uploadFile, controller.file_upload);
  1. 修改控制器的file_upload方法
    去掉手动调用uploadFile的代码,直接处理上传后的结果:
exports.file_upload = (req, res) => {
    const number = req.params.number;

    if (req.file == undefined) {
        return res.status(400).send({ message: "Please upload a file!" });
    }

    if (req.file) {
        return res.status(200).send({
            message: "Uploaded the file successfully: " + req.file.originalname,
        });
    }

    // 处理Multer抛出的错误(会自动被Express错误处理机制捕获)
    res.status(500).send({
        message: `Could not upload the file: ${req.file?.originalname || 'unknown'}`
    });
};

方法二:手动将uploadFile包装为Promise(适合必须在控制器内处理的场景)

如果一定要在控制器方法内调用上传逻辑,需要把Multer的回调式接口包装成Promise,并传入空的next函数:

exports.file_upload = async (req, res) => {
    const number = req.params.number;

    try {
        // 包装为Promise,同时传入空的next函数
        await new Promise((resolve, reject) => {
            uploadFile(req, res, (err) => {
                if (err) reject(err);
                else resolve();
            });
        });

        if (req.file == undefined) {
            return res.status(400).send({ message: "Please upload a file!" });
        }

        res.status(200).send({
            message: "Uploaded the file successfully: " + req.file.originalname,
        });
    } catch (err) {
        if (err.code == "LIMIT_FILE_SIZE") {
            return res.status(500).send({
                message: "File size cannot be larger than 2MB!",
            });
        }

        res.status(500).send({
            message: `Could not upload the file: ${req.file?.originalname || 'unknown'}. ${err}`,
        });
    }
};

内容的提问来源于stack exchange,提问作者Trocas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 19:30:42