4

I want to make a http PUT request with zip file in binary to a web api and get response with http status code.

How to read the file and PUT it with binary ?

Thank you for your help!!

1
  • it works find by using http-request module. http.put({ url: '', reqBody: fs.createReadStream(‘aa.zip'), headers: {'Content-Type':'application/zip'} }, function (err, res) { if (err) { console.error(err); return; } console.log(res.code, res.headers); }); Commented Apr 10, 2015 at 6:56

3 Answers 3

8

You can start with this:

var http = require('http');
var fs   = require('fs');

var req = http.request({
  hostname : HOSTNAME,
  port     : PORT,
  path     : UPLOAD_PATH,
  method   : 'PUT',
});

fs.createReadStream('somefile.zip').pipe(req);

You may need to perform some other actions, like proper error handling, setting Content-Type headers, etc.

Sign up to request clarification or add additional context in comments.

6 Comments

After fs.createReadStream('somefile.zip').pipe(req); How can I make the put request ?
var stream = fs.createReadStream('somefile.zip').pipe(req);
req.on('error', function(e) { console.log('problem with request: ' + e.message); });
fs.createReadStream('aaa.zip').pipe(request.put(options, function(err, res, data) { if(err) console.log('err: ' + err); else console.log(data); })); But it shows : A header you provided implies functionality that is not implemented .. but I did not set any header in the options, it only contains the uri : var options = { uri:'aaa.zzz' };
@KevingoTsai http.request() makes the PUT request when you pipe the file through it. You seem to be using the request module, which is fine, but it works (a bit) differently than the plain http module that I'm using. As for headers, it really depends on the exact semantics of the API implementation. Perhaps it requires certain headers to be set, I don't know.
|
5

Using request-promise (based on bluebird)

const fs = require('fs');
const request = require('request-promise');

const options = {
    method: 'PUT',
    url: 'dest url',
    qs: {key: 'value'}, // optional 
    headers: {
        'content-type': 'application/octet-stream'
    }
};

fs.createReadStream(zipFilePath).pipe(request(options)).then(body =>{
        console.log(body);
    })
    .catch(err => {
        console.log(err);
    });

Comments

0

Check that answer.

The only difference would be, you are using .put() instead on .post().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.