使用Formdata ajax和busboy的fileupload

时间:2016-12-09 15:13:43

标签: node.js file-upload

我想使用html5文件API上传带有ajax的文件,但是我在服务器端(node.js)保存文件时遇到了麻烦

我正在使用busboy,但是busboy不会触发文件事件,只是一个字段事件。

客户机侧:

upload.prototype.sendFile = function(fileData){
  var formData = new FormData()
  formData.append('test.jpg',fileData)
  var xhr = new XMLHttpRequest();
  xhr.open("post", "/file/upload", true);
  xhr.send(formData)
}

服务器端:

app.post('/file/upload',function(req,res,next){
  var busboy = new Busboy({ headers: req.headers });
  busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
    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, encoding, mimetype) {
    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);
})

0 个答案:

没有答案