Hello,
I am struggling trying to upload a PNG image to a web site, in order to publish my documentation work on a Confluence page.
I am able to do it perfectly using Python requests, but I need to use Nashorn Java Script in order to automate this image upload from a design tool
The POST actually works and the the image is uploaded (HTTP return code 200).
Unfortunately, the uploaded image binary code does not match the original file.
I suspect a character set conversion issue, but I do not succeed to solve it, being a newbie in Java Script.
I tried to force different charset setting, but without success...
Here a snippet of the code. Does it trigger some suggestion from the Community ?
Thanks
Xavier
--------------------------------------------------------------------------------------------------------------------------
function httpSendImage(method, theUrl, files, headers) {
method = method || 'POST';
lineEnd = "\r\n";
twoHyphens = "--";
boundary = "***232404jkg4220957934FW**";
var existingFileName='';
maxBufferSize = 1 * 1024 * 1024;
// Post Client request
try {
var con = new java.net.URL(theUrl).openConnection();
con.doOutput=true;
con.doInput=true;
con.useCaches=false;
con.requestMethod = method;
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
var filesData ='';
if (files != undefined) {
for (var prop in files) {
if (prop === 'filename') {
existingFileName = files[prop];
fileparts = existingFileName.split("\\");
files[prop] = fileparts[fileparts.length-1];
}
filesData += prop + '=\"' + files[prop] + '\"; ';
}
filesData = filesData.substring(0, filesData.length-2);
}
if (headers != undefined) {
for (var prop in headers) {
con.setRequestProperty(prop ,headers[prop]);
}
}
if (authorization != null) {con.setRequestProperty("Authorization", authorization);}
var dos = new java.io.DataOutputStream(con.outputStream);
var buf = Java.type('byte[]');
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; " + filesData + "\nContent-Type: image/png; charset=utf-8" + lineEnd);
dos.writeBytes(lineEnd);
// write bytes into form...
buf = readFile(existingFileName);
// console.log('buf length: ' + buf.length);
dos.writeBytes(buf);
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
dos.flush();
dos.close();
return asResponse(con);
}
catch(err) {
console.log("Error sending file: " + err.message);
}