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

Next.js中BusBoy的file事件未触发,请求排查问题

问题分析与解决

后端接口核心问题

你的后端代码里,res.status(203).send({ message: 'failed' });是同步执行的,而BusBoy的file/close/finish事件都是异步触发的。一旦调用res.send(),HTTP响应就直接结束,Node.js会终止请求处理流程,后续BusBoy的事件自然不会被触发。

解决方法:移除最后那行提前发送响应的代码,只在BusBoy的事件逻辑里返回响应,同时增加错误捕获避免请求挂起:

const busboy = require('busboy')

export default function handle(req, res) {
    const bb = busboy({headers: req.headers});
    
    bb.on('file', (fieldname, file, filename, encoding, mimetype) => {
        console.log(`收到文件:${filename},MIME类型:${mimetype}`);
        // 若不需要处理文件内容,调用file.resume()让流继续流转
        file.resume();
    });
    
    bb.on('close', () => {
        console.log('BusBoy流已关闭');
    });
    
    bb.on("finish", () => {
        res.status(202).send({ message: '文件上传处理完成' });
    });
    
    bb.on("error", (err) => {
        console.error('BusBoy处理错误:', err);
        res.status(500).send({ message: '文件处理失败', error: err.message });
    });
    
    req.pipe(bb);
}

前端代码问题

前端里headers: form.getHeaders是错误写法,getHeaders是方法,需要调用它:headers: form.getHeaders()。其实axios在发送FormData时,会自动设置包含boundary的正确Content-Type,所以你甚至可以直接去掉这个headers配置,让axios自动处理。

修正后的前端代码:

function onFileUpload(e) {
    e.preventDefault();
    let form = new FormData();
    form.append("image", file, file.name);
    
    axios({
        method: "post",
        url: "http://localhost:3000/api/uploadImage",
        data: form
    })
    .then((res) => {
        console.log(res);
    })
    .catch((err) => {
        console.error('上传失败:', err);
    });
}

另外要确保file变量是正确获取的,比如通过input的change事件拿到File对象:

let file;
function onFileChange(e) {
    file = e.target.files[0];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 09:15:38