使用node和restler进行多部分表单数据POST

时间:2013-03-21 04:03:31

标签: node.js http post multipartform-data restler

我可以使用数据部分中的restler.file上传文件,没有任何问题。我现在正在尝试编写一个非常短的CSV数据字符串,我无法找到数据函数的文档,但是阅读我认为我认为正确的代码:

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和其他东西添加到第3个arg,但我知道我错过了一些东西。我上面的数据字符串与我使用restler.file时的工作文件完全相同。如果在发布之前没有必要,我宁愿不写出CSV文件。

1 个答案:

答案 0 :(得分:5)

编辑----

根据@Joni对上述问题的评论,在通过pull request提交修复后,此问题似乎已得到纠正。

原始答案(来自OP)----

从对restler的研究(与维护者相对应)看起来,restler可以做我想做的事。注意:有人提交了一些代码,允许文件以流的形式出现,但是它没有被接受到分支中,而且我没有足够的流经验。

我解决了回归基础的问题。我阅读了RFC for multipart(http://www.ietf.org/rfc/rfc2388.txt),发现在构造正文时只需要注意一些规则,大多数是在正确的位置加上\ r \ n和' - '。

我决定简单地格式化原始POST主体并通过基本节点http client发送它。

这有效:

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

我希望这可以帮助人们做多部分/表格数据。