2

I'm using the Busboy to parse multipart/form-data in my server, and I want to store each file in a Buffer without automatically convert to utf8. Is it possible?

  const result = { files: [] }

  const busboy = new Busboy({
    headers: req.headers
  })

  busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
    const temp = {}

    file.on('data', (data) => {
      temp.file += data
    })

    file.on('end', () => {
      temp.filename = filename
      temp.contentType = mimetype
      result.files = [...result.files, temp]
    })
  })

  busboy.on('field', (fieldname, value) => {
    result[fieldname] = value
  })

  busboy.on('error', (error) => {
    console.error(error)
  })

Currently the file.on('data') doesn't work properly, I'm loosing information because the operation += automatically converts the buffer to utf8.

FXux
  • 415
  • 6
  • 15

1 Answers1

2

You can set temp.file to be an array instead of a string and concat the buffer array in the end.

  busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
    const temp = {file: []}

    file.on('data', (data) => {
      temp.file.push(data)
    })

    file.on('end', () => {
      temp.file = Buffer.concat(temp.file)
      temp.filename = filename
      temp.contentType = mimetype
      result.files = [...result.files, temp]
    })
  })
gnuns
  • 596
  • 5
  • 12