ServiceNow script to convert the image into base64Encoded strings (big string).

Abhishek_Thakur
Mega Sage

You can convert your image into base64 encoded string in ServiceNow with the help of below script include.

 

var BigEncoder64 = Class.create();

BigEncoder64.prototype = {
    initialize: function() {
    },

    GetBase64EncodedString: function(attachment_sys_id) {
        var StringUtil = new GlideStringUtil();
        var gsis = GlideSysAttachmentInputStream(attachment_sys_id);
        var baos = new Packages.java.io.ByteArrayOutputStream();
        gsis.writeTo(baos);
        baos.close();
        var base64Data = StringUtil.base64Encode(baos.toByteArray());
        return base64Data;  
    },

    type: 'BigEncoder64'
};
You can call this from any server side script like business rule. Below is the example.

var toto = new global.BigEncoder64();

gs.print(toto.GetBase64EncodedString('Your_SysId_of_A_big_Attachment'));

 

Please Mark this article helpful, if it helps you to achieve your requirements.

1 REPLY 1

Ahana 01
Tera Expert


Here is a sample script to convert an image into a base64 encoded string in ServiceNow:

javascript
var gr = new GlideRecord('sys_attachment');
gr.addQuery('table_name', 'incident');
gr.addQuery('table_sys_id', 'incident_sys_id'); // replace with your incident sys_id
gr.query();
if (gr.next()) {
var sa = new GlideSysAttachment();
var binData = sa.getBytes(gr);
var base64Str = GlideStringUtil.base64Encode(binData);
gs.info(base64Str);
}


This script does the following:

- Creates a new GlideRecord on the 'sys_attachment' table.
- Adds a query to filter the attachments related to a specific incident record.
- Queries the database for the attachment record.
- If an attachment is found, it gets the binary data of the attachment.
- Converts the binary data into a base64 encoded string.
- Logs the base64 encoded string to the system logs.

Please replace 'incident' and 'incident_sys_id' with your actual table name and record sys_id.


nowKB.com

For a good and optimistic result, and solving ServiceNow-related issues please visit this website.https://nowkb.com/home
Kindly mark correct and helpful if applicable