Express+Busboy文件上传

355 阅读1分钟
xx.post('/upload', function (req, res) {
    //defParamCharset预防上传文件名中文乱码
    const bb = busboy({ headers: req.headers, defParamCharset: 'utf-8' })
    bb.on('file', (name, file, info) => {
        const { filename } = info
        //根据系统的home目录编写文件保存路径
        const saveTo = path.join(os.homedir(), `../data/images/${filename}`);
        res.data = filename
        file.pipe(fs.createWriteStream(saveTo));
    });
    bb.on('error', (err) => {
        console.log(err)
    })
    bb.on('close', () => {
        res.send({
            code: 200,
            data: `http://localhost/images/${res.data}`
        });
    });
    req.pipe(bb);
    return
})

实践中遇到问题

1671374743719.png

最开始用postman+formdata上传文件,content-type+boundary都正确提交。 调用一直报这个错,从代码层面及github相关issues找到的原因各式各样都有。换别的中间件也有相似的问题。 最后把问题锁定在了postman发起的这个请求, 简单一个demo用fetch提交了formdata文件,实测成功。