节点js通过jquery表单数据错误发送post请求

时间:2014-07-17 19:31:03

标签: javascript jquery node.js form-data ajaxform

我想通过jQuery post请求发送文件。我的node.js将读取该文件并将data插入Mongodb。

这是我的node.js函数:

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

如果直接从post发送html请求,则上述功能正常,如下所示:

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

现在我想从jQuery提交post请求,并将响应data处理为:

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

这是投掷 Cannot read property 'filename' of undefined at FileName = files[0].filename error

如果我发送这样的请求:

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 抛出 Uncaught TypeError: Illegal invocation error

如果我从html发送post请求,一切正常。

如何从具有文件内容的j​​Query发送post请求?

2 个答案:

答案 0 :(得分:1)

第二个代码段的问题在于您错误地设置了内容类型,mutipart-formdata需要一个边界。但是,当您将FormData对象传递给$ .ajax时,如果将contentType和processData设置为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);

    }
});

答案 1 :(得分:0)

上面的答案对我有用。如果它没有用,你可以尝试使用javascript中的这个。工作正常。

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