send form with upload file in nodejs

1.3k views Asked by At

i use busbody to upload file in nodejs i can upload file but i cant get text message in bodyparser my fornt end code is :

<script>
    $("input[type='button']").click(function(){
    var files = $("input[type='file']").get();

    var formData = new FormData();
    var text  = "xxxxx";
    var url  = "fileUpload";
    if (files.length > 0){
      for (var i = 0; i < files.length; i++) {
        var input = $("input[type='file']").get(i).files;
        var file = input;
        if(file.length>0){
          console.log( file[0].name);
          formData.append('userpic',file[0], file[0].name);
        }
      }
      formData.append('text',text);
      $.ajax({
        type: "post",
        url: url,
        processData: false,
        contentType: false,
        data: formData, // serializes the form's elements.
      });
    }
  });
</script>

server.js

router.post('/fileUpload', function(req, res) {
console.log(req.body.text);
// req.pipe(req.busboy);
req.busboy.on('file', function(fieldname, file, filename) {
    console.log('ok2');
    var fstream = fs.createWriteStream('./public/images/' + filename);
    file.pipe(fstream);
    fstream.on('close', function () {

    });
});
res.send('upload succeeded!');
});

this line of code console.log(req.body.text); just return {}

2

There are 2 answers

1
schad On

Try using body-parser: npm install --save body-parser and then select middleware: var bodyParser = require('body-parser'); app.use(bodyParser.json());

Or use the middleware directly: var bodyParser = require('body-parser'); router.post('/fileUpload', bodyParser.json(), function(req, res) {....});

Also try using console.log(req.body) to look at format of the request.

0
NBeydon On

I think this is because of this line: file.pipe(fstream);, this should be fstream.pipe(file).

And like Steven say multer is a good alternative.