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?
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);
    }
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With