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

Node.js原生http服务接收的multipart/form-data如何解析为JSON

实现方案

multipart/form-data格式会通过请求头指定的boundary作为分隔符拆分各个表单字段,每个字段块由字段头、空行、字段值三部分组成,按照这个规则拆解原始内容即可转换为JSON格式。

完整实现代码

const http = require('http')
const server = http.createServer((req, res) => {
    // 仅处理multipart/form-data类型的POST请求
    if (req.method === 'POST' && req.headers['content-type']?.startsWith('multipart/form-data')) {
        const buffer = []
        // 从请求头提取分隔符boundary
        const boundary = req.headers['content-type'].split('boundary=')[1]

        req.on('data', chunk => {
            buffer.push(chunk)
        })

        req.on('end', () => {
            const rawStr = Buffer.concat(buffer).toString()
            const formData = {}
            
            // 用boundary分割所有内容块
            const parts = rawStr.split(`--${boundary}`)
            // 过滤无效块:空内容、结束标记块
            const validParts = parts.filter(part => part.trim() && part.trim() !== '--')

            validParts.forEach(part => {
                // 拆分头部和字段值,中间隔了两个标准http换行
                const [headerBlock, valueBlock] = part.split('\r\n\r\n')
                if (!headerBlock.includes('Content-Disposition: form-data')) return
                // 匹配表单字段的name属性
                const nameMatch = headerBlock.match(/name="([^"]+)"/)
                if (nameMatch) {
                    const fieldName = nameMatch[1]
                    // 去除值首尾的换行和空白字符
                    const fieldValue = valueBlock.trim()
                    formData[fieldName] = fieldValue
                }
            })

            // 转为JSON格式字符串
            const jsonResult = JSON.stringify(formData, null, 2)
            // 测试输出,可按需处理jsonResult
            res.writeHead(200, {'Content-Type': 'application/json'})
            res.end(jsonResult)
        })
    } else {
        res.writeHead(400)
        res.end('仅支持multipart/form-data类型的POST请求')
    }
})

server.listen(3000, () => console.log('服务启动在3000端口'))

效果说明

用你提供的请求示例测试,最终输出的JSON为:

{
  "on": "testing function",
  "target": "backend"
}

注意事项

  • 以上实现仅适用普通文本类型的表单字段解析,若需要支持文件上传,额外处理Content-Type为文件类型的块、读取二进制内容即可扩展。
  • 若请求中存在同名字段,可自行调整逻辑改为数组存储多个值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 11:39:01