Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js sending post request through jquery form data error

I want to send a file through jQuery post request. My node.js will read the file and insert data into Mongodb .

This is my node.js function:

upload: function(req, res){
    var FileName;
      req.file('myFile').upload(function(err,files){
      var i = 1;
        if(err) return res.serverError(err);
      FileName = files[0].filename; ......

The above function works fine if sent a post request directly from html as below:

<form method="post" action="/indi id="indiform" enctype="multipart/form-data">
        <input type="file" name="myFile" id="myIndifile"/>
        <input type="submit" id="indisubmitbutton" value="Submit" name="upload" class="btn btn-primary" id = "uploadFile"/>   
</form>

Now I want to submit the post request from jQuery and process the response data as:

var file = $("#myIndifile")[0].files[0];
$.ajax({
    type: 'post',
    url: '/indi',
    async: false,
    data: JSON.stringify({ myFile:file }),
    contentType: "application/json",
    success: function (data) {
      alert(" Number of lines Read  :"+data[0].lines+"\n"+"Number of records saved:"+data[1].saved);        
    }
  });

This is throwing Cannot read property 'filename' of undefined at FileName = files[0].filename error.

If I send request like this:

var file = $("#myIndifile")[0].files[0];
var formdata = new FormData();
formdata.append("myFile", file);
  $.ajax({
    type: 'post',
    url: '/indi',
    data: formdata,
    contentType: "multipart/form-data",
    success: function (data) {
      Pace.stop;
      alert(" Number of lines Read  :"+data[0].lines+"\n"+"Number of records saved:"+data[1].saved);        
    }
  });

javascript throws Uncaught TypeError: Illegal invocation error.

Everything is working fine if I send post request from html.

How to send post request from jQuery which has a file content?

like image 654
sanath_p Avatar asked Nov 01 '22 20:11

sanath_p


1 Answers

The problem with your second code snippet is that you set the content type incorrectly, a boundary is needed for mutipart-formdata. However when you pass a FormData Object to $.ajax it sets the correct content type and a boundary for you if you set the contentType and processData to false.

var file = $("#myIndifile")[0].files[0];
var formdata = new FormData();
formdata.append("myFile", file);
  $.ajax({
    type: 'post',
    url: '/indi',
    data: formdata,
    contentType: false,
    processData: false,
    success: function (data) {
      Pace.stop;
      alert(" Number of lines Read  :"+data[0].lines+"\n"+"Number of records saved:"+data[1].saved);

    }
});
like image 130
Musa Avatar answered Nov 09 '22 13:11

Musa