I'm attempting to send information to an external API. To quote their support:
"The file should be encoded in Base64 and inserted into the image parameter. "
I'm not sure if I'm misunderstanding something fundamental, but I am getting a 414-URI Too Large when I try to do so.
I wrote a short node.js script to do it:
var fs = require('fs');
var request = require('request');
var host = "api.xxxxx.com";
var app_id = "xxxxxxxx";
var app_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var sessionID = null;
function base64_encode(filename) {
// read binary data
var data = fs.readFileSync('./images/' + filename);
// convert binary data to base 64 encoded string
return new Buffer(data).toString('base64');
}
function start() {
fs.readdir('./images/', function(err, files) {
if (err) {
console.log("Error in fs.readdir: ", err);
}
else {
files.forEach(function(file) {
var base = base64_encode(file);
request.post({
url: 'https://api.xxxxxxx.com/media?source=' + base,
headers: {
'app_id': app_id,
'app_key': app_key
}}, function (error, response, body) {
if (response) {
console.log('Status:', response.statusCode);
console.log('Headers:', JSON.stringify(response.headers));
console.log('Response:', body);
}
else {
console.log("No response.");
}
});
});
}
})
}
start();
I've also tried putting the encoded image in form: {}, qs: {}, and moved it basically all over the place - i either get a "Required source parameter missing" error, or if I seem to get it right, I get the 414. Any advice on sending an image this way? It is a 144KB image.
Edit:
I changed the meat of the code to this:
files.forEach(function(file) {
var data = base64_encode(file);
var options = {
host: host,
port: 443,
path: '/media',
method: 'POST',
headers: {
'app_id': app_id,
'app_key': app_key,
'Content-Type': 'image/jpg',
'Content-Length': data.length
}
};
var req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
});
But I am still getting "required source parameter missing" as a response. How do I specify it as the "source" parameter?