A common use case when working with integrations in ServiceNow is dealing with attachments in base64 format. However, the information on how to accomplish this is often scattered across different sources. This article aims to provide clear and effective code snippets to simplify the process.
Attachment to Base64
The following function converts a ServiceNow attachment to base64.
/* attGr is a GlideRecord from sys_attachment table */
function attachmentToBase64(attGr) {
/* constructor of GlideSysAttachment class */
var gst = new GlideSysAttachment();
/* fetching the attachment content in bytes */
var bytes = gst.getBytes(attGr);
/* encoding the bytes in base64 format */
var base64Content = GlideStringUtil.base64Encode(bytes);
return base64Content;
}
Base64 to Attachment
The following function converts base64 content to a ServiceNow attachment.
/* recordGr is the GlideRecord for the record where the file needs to be uploaded */
/* att_name is the file name for the attachment */
/* att_content_type contains the file type, eg. application/pdf */
/* att_payload contains the base64 content for the attachment */
function base64ToAttachment(recordGr, att_name, att_content_type, att_payload) {
/* constructor of Attachment class */
var attachment = new Attachment();
/* writing the attachment to the database */
attachment.write(recordGr.getTableName(), recordGr.getUniqueValue(), att_name, att_content_type, GlideStringUtil.base64DecodeAsBytes(att_payload));
}