如何使用节点http库中的post请求上传文件?

bne*_*eil 3 http node.js

从Node.js http库文档:

http.request() returns an instance of the http.ClientRequest class. 
The ClientRequest instance is a writable stream. If one needs to upload a file 
with a POST request, then write to the ClientRequest object.
Run Code Online (Sandbox Code Playgroud)

但是我不确定如何在我当前的代码中利用它:

var post_data = querystring.stringify({
    api_key: fax.api_key,
    api_secret: fax.api_secret_key,
    to: fax.fax_number,
    filename: ""
});

var options = {
    host: p_url.hostname.toString(),
    path: p_url.path.toString(),
    method: 'POST',
    headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': post_data.length
    }
};

var postReq = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
    });
});

postReq.write(post_data);
postReq.end();
Run Code Online (Sandbox Code Playgroud)

hex*_*ide 6

既然你有写流,你可以使用write(),end()并且pipe()它的方法.因此,您只需打开一个资源,并将其传递给可写流:

var fs = require('fs');
var stream = fs.createReadStream('./file');
stream.pipe(postReq);
Run Code Online (Sandbox Code Playgroud)

或类似的东西:

var fs = require('fs');
var stream = fs.createReadStream('./file');

stream.on('data', function(data) {
  postReq.write(data);
});

stream.on('end', function() {
  postReq.end();
});
Run Code Online (Sandbox Code Playgroud)