I'm trying to send an image to remote server from nodejs server. Here's the request format so far.
Note: Just like binary request in postman and choosing a file and sending)
function upload(options, body) { body = body || ''; return new Promise(function(resolve, reject){ const https = require('https'); https.request(options, function(response) { var body = []; response.on('data', function(chunk) { body.push(chunk); }); response.on('end', function(){ resolve(JSON.parse(Buffer.concat(body).toString())) }); }).on('error', function(error) { reject(error); }).end(body); }); }
Use:
var options = { hostname: "hostname", path: "/upload", port: 443, method: 'PUT', headers: { 'Accept': 'application/json', 'Content-Type': 'image/png' } }; fs.readFile('./img/thumbnail.png', function(error, data) { options.body = data; upload(options).then(... });
Edit 2
After several attempts, came across an efficient strategy to upload images via streams, here's how it looks like but still not success.
const https = require('https'); var request = https.request(options, function(response) { var buffers = []; response.on('data', function(chunk) { buffers.push(chunk); }); response.on('end', function(){ console.log(response.headers['content-type']); var body = JSON.parse(buffers.length ? Buffer.concat(buffers).toString() : '""'); response.statusCode >= 200 && response.statusCode < 300 ? resolve(body) : reject(body); }); }).on('error', function(error) { reject(error); }); const fs = require('fs'); var readStream = fs.ReadStream(body.path); readStream.pipe(request); readStream.on('close', function(){ request.end(); });