如何在Node.js的http库中使用POST请求上传文件?

4

来自 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.

但是我不确定如何在我的当前代码中利用这个功能:

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();
1个回答

8

既然你有一个可写流,你可以在其上使用write()end()pipe()方法。因此,你只需打开一个资源,并将其管道传输到可写流中:

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

或者像这样:

或者类似于此:

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

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

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

1
但是等等.. data 不就是请求体吗?我怎么能获取文件/图像并使用表单数据的参数(我的请求体数据)呢? - IvRRimUm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接