Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Send Attachment from ServiceNow to Connectwise using multipart/form-data

ramesh_r
Mega Sage

Hi All,

 

I am trying to send document Send Attachment from ServiceNow to Connectwise using multipart/form-data

the below code is working only for txt and XML files but its not working for the any other file type ex : doc or png

var gr = new GlideRecord('sys_attachment');
gr.addQuery('sys_id', '872966331badfsfsdf4604bcb71');
gr.query();
if (gr.next()) {
var sa = new GlideSysAttachment();
var binData = sa.getBytes(gr);

// Convert the binary data to a string assuming it's a text file
var textContent = '';
for (var i = 0; i < binData.length; i++) {
textContent += String.fromCharCode(binData[i]);
}

var fileName = gr.file_name; // file name
var recordId = '2808562'; // ticket ID
var recordType = 'Service'; // recordType

var request = new sn_ws.RESTMessageV2();
request.setEndpoint('https://connectwise.hightouchinc.com/v4_6_release/apis/3.0/system/documents');
request.setHttpMethod('POST');
request.setRequestHeader('clientId', '7e76rer332-b276-4343fa-87e2-0423478d330');
request.setRequestHeader('Authorization', 'Basic VFJBSU5JTkcR2S4sddsfFZNVhlY2hPWnhU');

// Adding form data
request.setRequestBody(
'--boundary\r\n' +
'Content-Disposition: form-data; name="file"; filename="' + fileName + '"\r\n' +
'Content-Type: text/plain\r\n\r\n' + textContent + '\r\n' +
'--boundary\r\n' +
'Content-Disposition: form-data; name="recordId"\r\n\r\n' + recordId + '\r\n' +
'--boundary\r\n' +
'Content-Disposition: form-data; name="recordType"\r\n\r\n' + recordType + '\r\n' +
'--boundary\r\n' +
'Content-Disposition: form-data; name="file_name"\r\n\r\n' + fileName + '\r\n' +
'--boundary--'
);

request.setRequestHeader('Content-Type', 'multipart/form-data; boundary=boundary');

var response = request.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();

gs.info('Response Body: ' + responseBody);
gs.info('HTTP Status: ' + httpStatus);
}
2 REPLIES 2

Muhammad Arif B
Tera Contributor

Hi Ramesh, i also have the requirement same as you. Can you help to share the REST Message table side?

Hi @ramesh_r  & @Muhammad Arif B 

When sending binary files (like DOC or PNG) using multipart/form-data, you need to handle the binary data differently than you would with text files. In particular, you should not convert the binary data to a string; instead, you should send it as is.

 

I hope my answer helps you to resolve your issue, if yes please mark my answer helpful and correct.

thank you

Rajesh