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

如何修复使用Fetch上传图片时出现的'multipart: NextPart: bufio: buffer full'错误?

头像上传报错"multipart: NextPart: bufio: buffer full"的解决方法

问题场景

网站通过Fetch POST请求实现头像上传功能,使用以下请求代码:

async function uploadAvatar(data, token) {
    return  await fetch(`${apiBase}upload/avatar`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryEmKNDsBKjB7QEqu',
            'Authorization': `Bearer ${token}`
        },
        body: data
    });
}

表单提交处理函数:

const onUploadAvatar = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    try {
        const response = await uploadAvatar(formData, localStorage.getItem('token'));
        if (response.ok) {
            console.log('ok');
        } else response.json().then((res) => {
            createError(res.message);
        })

    } catch (error) {
          console.log(error);
    }
}

提交表单时出现错误:multipart: NextPart: bufio: buffer full

错误原因

手动设置了Content-Type的boundary值,但当请求body是FormData对象时,浏览器会自动生成并设置正确的boundary,手动指定的固定boundary和实际请求中FormData生成的不匹配,导致后端在解析multipart表单数据时无法正确分割各个部分,最终触发缓冲区溢出的错误。

修复方法

移除请求头中手动设置的Content-Type字段,让浏览器自动处理multipart/form-data的boundary:

修改后的uploadAvatar函数:

async function uploadAvatar(data, token) {
    return  await fetch(`${apiBase}upload/avatar`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Authorization': `Bearer ${token}`
            // 移除手动设置的Content-Type
        },
        body: data
    });
}

当body为FormData时,浏览器会自动添加正确的Content-Type头(包含自动生成的boundary),这样后端就能正常解析表单数据,解决缓冲区溢出的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:53:09