Attachments API - Converting Binary Files to Base64

Lucas Romani1
Tera Contributor

Hi,

I am using a REST API from servicenow (/api/now/attachment/{sys_id}/file) to get the binary file of an attachment (code below)

var rest = new sn_ws.RESTMessageV2();
rest.setEndpoint('https://xxxxxxxxxx.service-now.com/api/now/attachment/6f20c5fe1bbe6d10e641eb5be54212/file');
rest.setHttpMethod('get');
rest.setRequestHeader("Accept",'*/*');
rest.setBasicAuth("user","password");
var response = rest.execute();
var obj = response.getBody();
gs.info(obj); /* obj is the binary representation of the attachment */

Is there a way to convert the binary file (obj) to base64 ? I tried using GlideStringUtil.base64Encode(obj) but it seems not correct. Can you help me ?

1 ACCEPTED SOLUTION

Ratnakar7
Mega Sage
Mega Sage

Hi @Lucas Romani1 ,

 

You can use the GlideStringUtil.base64Encode() method to convert the binary file to Base64 in ServiceNow. Here's an updated version of the code using GlideStringUtil.base64Encode():

 

 

var rest = new sn_ws.RESTMessageV2();
rest.setEndpoint('https://xxxxxxxxxx.service-now.com/api/now/attachment/6f20c5fe1bbe6d10e641eb5be54212/file');
rest.setHttpMethod('get');
rest.setRequestHeader("Accept", '*/*');
rest.setBasicAuth("user", "password");
var response = rest.execute();
var obj = response.getBody(); // obj is the binary representation of the attachment

var base64String = GlideStringUtil.base64Encode(obj);

gs.info(base64String); // base64String is the Base64 representation of the binary file

 

 

 

For converting large files to base64encode string, you can refer below script:

 

 

var StringUtil = new GlideStringUtil();

var gsis = GlideSysAttachmentInputStream(gr.sys_id.toString());

var ba = new Packages.java.io.ByteArrayOutputStream();

gsis.writeTo(ba);

baos.close();

var base64EncodedData = StringUtil.base64Encode(ba.toByteArray());

 

 

 

If my response was helpful in resolving the issue, please consider accepting it as a solution by clicking on the Accept solution button and giving it a thumbs up 👍. This will benefit others who may have a similar question in the future.

 

Thank you!

Ratnakar

View solution in original post

6 REPLIES 6

Hi @SrikanthD1G ,

 

I have a similar requirement where I have to read the response (binary data) and attach the same in the incident record. Did you find the solution for your query ?

 

Ankur Bawiskar
Tera Patron
Tera Patron

@Lucas Romani1 

what's your requirement?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader