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();
});
uploadImage(options, body)
doesn't look right... where isbody
defined? – Anoleoptions.body
and is sent to the remote server with that key – Quintuplicatebinary
->options.body
and forraw
,x-www-form-urlencoded
andform-data
-> will go to body, please confirm or correct. – Playaon('data')
oron('end')
is getting called when I pass the image body inresponse.end(body)
function, any advice guys? – Playaapplication/octet-stream
, maybe the remote server expects octet-stream, not sure how I can specify this while sending the image data – PlayareadStream('close'
is not getting called, it's a 3.1 MB image – Playa