Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload file using a post request in the node http library?

Tags:

http

node.js

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();
like image 708
bneil Avatar asked Feb 16 '23 05:02

bneil


1 Answers

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

Or something like this:

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

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

stream.on('end', function() {
  postReq.end();
});
like image 162
hexacyanide Avatar answered May 14 '23 13:05

hexacyanide