2013-03-21 56 views
0

我能够在数据部分使用restler.file上传文件,没有任何问题。我现在想写一个很短的CSV数据串,这我无法找到数据函数文档,但阅读的代码我原本以为是正确的:将节点和restler用于多部分表单数据POST

restler.post("http://posttestserver.com/post.php", { 
    multipart: true, 
    data: { 
      "upload": restler.data("people.csv", "text/csv", '384;213;Status Update'), 
      "returnURL": "" 
    } 
}).on("complete", function(data) { 
    console.log(data); 
}); 

可惜,这只是挂和意志时间到。我尝试将EOF和其他东西添加到第三个参数,但我知道我错过了一些东西。上面的数据字符串与我使用restler.file时工作的文件完全相同。如果我在发布之前不必写出CSV文件,我宁愿不写。

+0

我从维护人员那里得到一个说明,restler.data函数也在等待一个文件,所以我不确定该怎么做。我采取了稍微不同的机智,但取得了我期望的结果。如果好奇,请看下面的答案。 – liquidki 2013-03-21 21:39:58

+1

旧的restler代码存在一个问题,如您在示例中那样执行restler.data调用将无法正确提交请求。无论如何,现在你的原始帖子已经在https://github.com/danwrong/restler/pull/172中修复了一年,现在对我来说工作正常。 – Joni 2014-06-13 00:42:20

回答

5

编辑----

按@乔尼对上述问题的评论,这个问题似乎修复经pull request提交后已纠正。

原来的答案(由OP)----

从上restler(并与保持相应的)研究它看起来并不像restler可以做我想要的。注意:有人提交了一些代码,允许以流的形式存在文件部分,但尚未被分支接受,并且我没有足够的流体验经验。

我解决了回到基础的问题。我阅读了多部分的RFC(http://www.ietf.org/rfc/rfc2388.txt),发现在构建身体时只需要注意几条规则,在正确的位置大部分是额外的\ r \ n和' - '。

我决定简单地格式化原始的POST正文并通过基本节点http客户端发送它。

这工作:

var http = require('http'); 

postBody = new Buffer(
    '------WebKitFormBoundaryebFz3Q3NHxk7g4qY' + "\r\n" + 
    'Content-Disposition: form-data; name="upload"; filename="filename.csv"' + "\r\n" + 
    'Content-Type: text/csv' + "\r\n" + 
    '\r\n' + 
    'comma,separated,values' + "\r\n" + 
    '------WebKitFormBoundaryebFz3Q3NHxk7g4qY' + "\r\n" + 
    'Content-Disposition: form-data; name="returnUrl"' + "\r\n" + 
    '\r\n' + 
    'http://return.url/' + "\r\n" + 
    '------WebKitFormBoundaryebFz3Q3NHxk7g4qY--' 
    ); 

var headers = { 
    "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryebFz3Q3NHxk7g4qY", 
    "Content-Length": postBody.length 
}; 

//These are the post options 
var options = { 
    hostname: 'myhost.com', 
    port: 80, 
    path: '/myPost', 
    method: 'POST', 
    headers: headers 
}; 

// so we can see that things look right 
console.log("postBody:\n" + postBody); 
console.log("postBody.length:\n" + postBody.length); 

var responseBody = ''; 

// set up the request and the callbacks to handle the response data 
var request = http.request(options, function(response) { 
    // when we receive data, store it in a string 
    response.on('data', function (chunk) { 
     responseBody += chunk; 
    }); 
    // at end the response, run a function to do something with the response data 
    response.on('end',function() { 
     console.log(responseBody); 
    }); 
}); 

// basic error function 
request.on('error', function(e) { 
    console.log('problem with request: ' + e.message); 
}); 

// write our post body to the request 
request.write(postBody); 
// end the request 
request.end(); 

我希望这可以帮助人们在做多/表单数据。

相关问题