Skip to content Skip to sidebar Skip to footer

Node Js Upload Binary File To Another Server

I've got an audio file which I post to a server for translation. I've managed to create a request in postman, but I do not know how to write the file to this server. Below is the c

Solution 1:

One solution that would easily fit into your current program without too much work is to make use of the form-data module on npm.

The form-data module makes ease of multipart requests in node. The following is a simple example of how to use.

var http = require("https");
varFormData = require('form-data');
var fs = require('fs')

var form = newFormData();
form.append('my_field', fs.createReadStream('my_audio.file'));

var options = {
  host: 'your.host',
  port: 443,
  method: 'POST',
  // IMPORTANT!headers: form.getHeaders()
}

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
   });
});

// Pipe form to request
form.pipe(req);

In a "real-world" scenario you would want to do a lot more error checking. Also, there are plenty of other http clients on npm that make this process easy as well (the request module uses form-data BTW). Check out request, and got if you are interested.

For sending a binary request the fundamentals are still the same, req is a writable stream. As such, you can pipe data into the stream, or write directly with req.write(data). Here's an example.

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

var options = {
  // ...headers: {
    'Content-Type': 'application/octet-stream'
  }
}

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
   });
});


var audioFile = fs.createReadStream('my_audio.file', { encoding: 'binary' });
audioFile.pipe(req);

Note, that if you use the write method explicitly req.write(data) you must call req.end(). Also, the you may want to take a look at the encoding options for Node's Buffer (docs).

Solution 2:

You can use the request package on npm.

Install the request module from npm: npm install request --save

Then use the request module to send your request.

Have a look at https://www.npmjs.com/package/request for details on implementation.

Solution 3:

Thanks @undefined, your answer really helped me.

I am posting my solution which worked for me to send file to another server using axios. Ignore the type specifications, I had Typescript enabled for my project.

exportconstfileUpload: RequestHandler = async (req: Request, res: Response, next: NextFunction) => {
    constchunks: any[] = [];
    req.on('data', (chunk) => chunks.push(chunk));
    req.on('end', () => {
        const data = Buffer.concat(chunks);
        axios.put("ANOTHER_SERVER_URL", data).then((response) => {
            console.log('Success', response);
        }).catch(error => {            
            console.log('Failure', error);
        });
    });
    return res.status(200).json({});
};

Thanks, hope it helps!

Post a Comment for "Node Js Upload Binary File To Another Server"