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

NestJS使用multipart/form-data上传文件到第三方API报错如何解决?

问题修复说明

错误原因

出现TypeError: source.on is not a function(中文翻译:类型错误:source.on 不是一个函数,错误位置在 Function.DelayedStream.create (C:\Users\Tushar\Squire-backend\node_modules\delayed-stream\lib\delayed_stream.js:33:10))的核心问题有两点:

  • form-data库只支持接收Buffer、可读流类型的文件内容,你直接传入完整的Express.Multer.File对象会被识别为普通JSON对象,不存在流对应的on方法,因此触发该报错。
  • 手动硬编码Content-Type: multipart/form-data请求头时,没有带上multipart请求必需的boundary边界参数,该参数由FormData实例自动生成,硬编码头会导致请求格式异常,第三方接口无法正确解析表单数据。

修复代码

调整uploadDocument服务方法即可:

async uploadDocument(file: Express.Multer.File){
        try{
        const formData = new FormData()
        // 传入文件buffer,同时指定原始文件名和MIME类型
        formData.append('file', file.buffer, {
            filename: file.originalname,
            contentType: file.mimetype
        })
        const response = await this.httpService.post(`urlWhereItHits`,
        formData, 
        {   
            headers:{ 
                "X-AppSecretToken":"appsecrettoken",
                "X-AgreementGrantToken":"agreementgranttoken",
                // 自动获取带boundary的正确formData头,替代手动写死的Content-Type
                ...formData.getHeaders()
            },
            // 允许传输大文件,避免体积超限被拦截
            maxContentLength: Infinity,
            maxBodyLength: Infinity
        }).toPromise();
        return response.data
        }
        catch(error){
            // 打印第三方接口返回的错误信息方便排查
            console.log(error.response?.data || error.message)
            throw error
        }
}

额外注意事项

  • 如果是TypeScript项目,需要提前安装@types/form-data依赖保证类型正确。
  • 控制器层返回完整file对象会包含完整buffer数据,会导致响应体积过大,建议只返回文件名、大小等必要字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:03:00