The problem may come up where you need to read data from an attachment file in your ServiceNow environment. This is made pretty simple by utilizing the ServiceNow GlideSysAttachment API. Let’s crack open a workflow and create a run script, or maybe even a “Fix Script” for testing.
//You can find attachment sys_id's on the 'sys_attachment' table
var attachment = new GlideSysAttachment();
//Grab the bytes data from the attachment
var fileBytes = attachment.getBytes("some_table", sys_id);
//Convert 'Bytes' to a string!
var contents = String(Packages.java.lang.String(fileBytes));
This is great for fetching the contents of the file. However, what if the file contents are in JSON and you’d like to use the great features of JSON from your file attachment.
Try adding this on the following lines of your code:
What is possible with ServiceNow GlideSysAttachment API?
In a new System Definitions -> Fix Scripts. Create one and write the following code.
Selecting “Run Fix Script”, select “OK” and run in the background. Then show your progress workers and check out the log!
You should see the following methods for the GlideSysAttachment API come up.
setTableName, getClass, fileName, streamData, getBytes, tableName, setFileName, getBytesUnsafe, getFileDescriptor, setContentType, getAsStream, getAttachmentsForExtensions, write, getFileName, contentType, getTableSysID, attachmentsForExtensions, renameAttachment, getParameter, processRequest, replaceContent, read, setStreamCipher, sysID, getTableName, changeEncryptionContext, bytesUnsafe, inputStream, asStream, addEncryptionContexts, getInputStream, getAttachments, getContentType, errorFileName, fixImageDimensions, getDBImageAttachmentRecord, parameters, wait, attachments, imageDimensions, readToFile, setImageDimensions, getSizeBytes, notifyAll, delete, notify, getErrorFileName, allAttachments, deleteAllAttachments, setInputStream, hashCode, get, tableSysID, parameter, getSysID, streamMonitor, readByName, DBImageAttachmentRecord, class, loadParameters, setStreamMonitor, writeFromRequest, streamCipher, deleteAll, errorMessage, setTableSysID, sizeBytes, writeInvisible, getAllAttachments, fileDescriptor, bytes, equals, writeParts, getParameters, exists, toString, deleteAttachment, getErrorMessage
As you can see there are a lot of valuable functions associated with the GlideSysAttachment object in ServiceNow. In the coming weeks I’ll be delving into some of the functionality of these specific methods, and how we can leverage them for our needs!
If you have any questions or how-to’s about ServiceNow, comment below or use my contact form to ask me.