sanath_p
sanath_p

Reputation: 2218

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?

Upvotes: 5

Views: 2319

Answers (2)

sanath_p
sanath_p

Reputation: 2218

The above answer worked for me .if in case it didnt worked, you can try this one which is in javascript.Both work fine.

var fd = new FormData;

    var file = document.getElementById('myIndifile').files[0];
    fd.append('myFile', file);
    var xhr = new XMLHttpRequest();
    xhr.file = file; 
    xhr.addEventListener('progress', function(e) {
        var done = e.position || e.loaded, total = e.totalSize || e.total;
        console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
    }, false);
    if ( xhr.upload ) {
        xhr.upload.onprogress = function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
        };
    }
    xhr.onreadystatechange = function(e) {
        if ( 4 == this.readyState ) {
            console.log(['xhr upload complete', e]);
            var resdata = JSON.parse(xhr.responseText);
            alert(" Number of lines Read  :"+resdata[0].lines+"\n"+"Number of records saved:"+resdata[1].saved);

        }
    };
    xhr.open('post', '/indi', true);
    xhr.send(fd);
});

Upvotes: 0

Musa
Musa

Reputation: 97717

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);

    }
});

Upvotes: 3

Related Questions