如何在node.js中发送和接收多部分数据?

时间:2016-10-06 11:12:59

标签: html node.js web webserver

这是我的HTML页面,我想发送图像文件和有关TODO任务和描述的信息。 http://pastebin.com/W9TVy4An

form.on('part', (part) => {
if (part.filename) {
  let imagePath = ''
  let privateIndex  // will hold the index for private images
  let index  // will hold the index for the public images
  let file = ''

  part.setEncoding('binary')
  part.on('data', (data) => {
    file += data
  })
  part.on('end', () => {

    if (isPrivate) {
      // handle a private image
    } else {
      // handle a public image

    }
    if (!fs.existsSync(imagePath)) {
      fs.mkdir(imagePath)  // create the folder for the image
    }

    imagePath += isPrivate ? privateIndex + '.jpg' : index + '.jpg'  // add the image name to complete the path for saving

    fs.writeFile(imagePath, file, 'ascii', (err) => {
      // stuff
      }
    })

    callback(part.filename)
  })

我知道如何使用node.js中的multiparty接收文件,如上所示,但我不能在我的生活中收到有关TODO任务的描述和名称的信息。

有人可以告诉我这样做的方法,还是指出我犯的一些愚蠢的错误?

1 个答案:

答案 0 :(得分:0)

好的,我找到了一种方法,在解析表单时阅读fieldsfiles属性。

let form = new multiparty.Form()
form.parse(req, (err, fields, files) => {
  console.log(fields)
})

Fields是一个对象,其属性名称为键,值为值。 结果是

{ todoname: [ 'Post the answer' ], tododesc: [ 'Post the answer you figured out on your StackOverflow question' ] }