busboy文件上传遇到的坑,已解决

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/meifannao789456/article/details/88662364

有个需求是需要实现文件上传的功能,原本打算参考koa2进阶教程中的busboy模块来实现:https://chenshenhai.github.io/koa2-note/note/upload/busboy.html,
示例代码:

const inspect = require('util').inspect 
const path = require('path')
const fs = require('fs')
const Busboy = require('busboy')

// req 为node原生请求
const busboy = new Busboy({ headers: req.headers })

// ...

// 监听文件解析事件
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
  console.log(`File [${fieldname}]: filename: ${filename}`)


  // 文件保存到特定路径
  file.pipe(fs.createWriteStream('./upload'))

  // 开始解析文件流
  file.on('data', function(data) {
    console.log(`File [${fieldname}] got ${data.length} bytes`)
  })

  // 解析文件结束
  file.on('end', function() {
    console.log(`File [${fieldname}] Finished`)
  })
})

// 监听请求中的字段
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
  console.log(`Field [${fieldname}]: value: ${inspect(val)}`)
})

// 监听结束事件
busboy.on('finish', function() {
  console.log('Done parsing form!')
  res.writeHead(303, { Connection: 'close', Location: '/' })
  res.end()
})
req.pipe(busboy)

代码很简单,在拿到http请求后,注册busboy的回调进行处理,在‘file’中进行文件写入操作,在‘finish’中任务完成进行http返回。
在实际使用过程中发现每次http请求后busboy直接回调了‘finish’,导致文件写入失败。

问题解决

后来发现是我的项目中已经使用了koa-bodykoa-body已经支持了文件上传,导致与busboy冲突,所以一直回调不到file,后面直接使用koa-body实现了上传功能。

猜你喜欢

转载自blog.csdn.net/meifannao789456/article/details/88662364
今日推荐