ast week I wrote about how to send a file to Service-now via web services and attach it to a target record.  While that is the most common request for attachment handling in regards to an integration, I often hear requests for this to be bidirectional.  Sending attachments from Service-now to a third-party system isn’t something that we’ve actually implemented in the past.  However, with the number of people asking for it lately, I decided to write up a solution.

Fetch Attachment as Base64 Encoded Data

The following code is assumed to be within a business rule on the task table (or a table that inherits from task, such as incident, problem, change, etc).

var StringUtil = Packages.com.glide.util.StringUtil;

var  gr = new GlideRecord('sys_attachment');
gr.addQuery('table_sys_id', current.sys_id);
gr.addQuery('table_name', current.getTableName());
gr.addQuery('file_name', &'truck7.jpg');

if (gr.next()){
  var sa = new  Packages.com.glide.ui.SysAttachment();
  var binData =  sa.getBytes(gr);
  var encData =  StringUtil.base64Encode(binData);
  gs.log('record not found');

The above code is where the magic happens.  The attachment to the incident is retrieved from the Service-now database and is now in base64 encoded data, ready to be sent to the integrating party via web services.

Send Attachment Data via SOAP

The code for sending the encoded data to a 3rd-party system might look something like this:

var envelope = new SOAPEnvelope();
envelope.createNameSpace('xmlns:imp', 'http://www.abcCompany.com/soap');
envelope.addFunctionParameter('uid', current.correlation_id);
envelope.addFunctionParameter('content', encData);
envelope.addFunctionParameter('content_type', gr.content_type);
var request = new SOAPRequest('http://www.abcCompany.com/addAttachment', 'user','pass');
var res = request.post(envelope);

Fetch Attachment Data – Alternate Method

You very well may want to have the business rule run on the sys_attachment table instead of the TASK table.  If this is the case, your business rule will look like the following:

var StringUtil = Packages.com.glide.util.StringUtil;

var sa = new   Packages.com.glide.ui.SysAttachment();
var binData =   sa.getBytes(current);
var encData =  StringUtil.base64Encode(binData);

Related Links: