如何使用节点http库中的发布请求上传文件? [英] How to upload file using a post request in the node http library?
本文介绍了如何使用节点http库中的发布请求上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从Node.js http库文档中:
From the Node.js http library docs:
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.
但是我不确定如何在当前代码中利用这一点:
However I'm unsure how to leverage this in my current code:
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();
推荐答案
由于具有可写流,因此可以在其上使用write()
,end()
和pipe()
方法.因此,您可以打开一个资源,然后将其通过管道传递到可写流:
Since you have a writable stream, you can use the write()
, end()
and pipe()
methods on it. Therefore, you can just open a resource, and pipe it to the writable stream:
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();
});
这篇关于如何使用节点http库中的发布请求上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文