How to get Base64 of a record from sys_attachment table

Alon Grod
Tera Expert

How to get Base64 of a record from sys_attachment table using business rule

2 REPLIES 2

Ankur Bawiskar
Tera Patron

@Alon Grod 

if you are in global scope then use this

var gr = new GlideRecord('sys_attachment');
	gr.get('d7ff2c044f96cc90fc11fa218110c746');

	var StringUtil = new GlideStringUtil();
	var gsis = GlideSysAttachmentInputStream(gr.sys_id.toString());
	var ba = new Packages.java.io.ByteArrayOutputStream();
	gsis.writeTo(ba,0,0);
	ba.close();
	var base64EncodedData = StringUtil.base64Encode(ba.toByteArray());
gs.info(base64EncodedData);

if you are using in scoped app then use this

var gr = new GlideRecord('sys_attachment');
gr.get('3fd6017407d3dc50540bf2508c1ed027');

var sysAtt = new GlideSysAttachment();

var base64Data = sysAtt.getContentBase64(gr);

gs.info(base64Data);

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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

vaishali231
Kilo Sage

Hey @Alon Grod 

 

Try this :

Business Rule (After Insert on sys_attachment)

Script :

(function executeRule(current, previous) {

    try {

        var stringUtil = new GlideStringUtil();

        var inputStream = new GlideSysAttachmentInputStream(current.sys_id.toString());

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

        inputStream.writeTo(outputStream, 0, 0);

        var base64 = stringUtil.base64Encode(outputStream.toByteArray());

        outputStream.close();

        gs.info("Base64: " + base64);

        // Use the Base64 value as required (REST payload, custom field, etc.)

    } catch (ex) {

        gs.error("Failed to generate Base64: " + ex);

    }

})(current, previous);

*************************************************************************************************************************************

If this response helps, please mark it as Accept as Solution and Helpful.

Doing so helps others in the community and encourages me to keep contributing.

Regards

Vaishali Singh

Servicenow Developer
Linkedin - https://www.linkedin.com/in/vaishali-singh-2273361bb