OBLYTECH Logo
OBLYTECH Logo

Attachment and Stream APIs in ServiceNow Server Scripts

Server scripts reach file attachments through the GlideSysAttachment class. It returns metadata, text, base64 strings or raw streams, and it can write, copy and delete attachments. Consumers such as GlideTextReader and GlideExcelParser take that stream directly. Pick the access method by scope and file size first, then build the rest of the script around it.

Choose the access method by scope and file size

GlideSysAttachment offers several ways to read the same file, and they do not behave alike. One method returns a string, a second returns a base64 encoded string, and a third returns a stream object that holds the untouched bytes.

Method What it returns Scope Practical use
getContent(attachmentRecord) The file text as a string Scoped Short CSV, JSON or plain text files
getContentBase64(attachmentRecord) A base64 encoded string Scoped Passing content to an API that expects encoded bytes
getContentStream(sysId) A GlideScriptableInputStream holding raw bytes Scoped and global Large files, binary files and any streaming consumer

getContent returns up to 5MB of text for CSV, JSON and text files. getContentBase64 returns up to 5MB of base64 encoded content. When getContent runs in the global scope, it returns undefined. A global script therefore builds around the stream method and passes that stream into a reader.

The stream is an opaque object. You obtain it from getContentStream and hand it to a consumer such as GlideTextReader, GlideExcelParser or XMLDocument2. The 5MB ceiling on string reads does not apply to a consumer that reads line by line from the stream. The reader’s own methods are covered in the GlideTextReader API guide.

Find attachments on a record and read their metadata

The getAttachments method takes a table name and a record sys_id, then returns a GlideRecord of attachment metadata. Each row carries fields such as the file name, content type and size.

var attachment = new GlideSysAttachment();
var files = attachment.getAttachments('incident', incidentSysId);
while (files.next()) {
  gs.info(files.getValue('file_name'));
}

Once you have a row, pass it to getContent to read the text of that single file. Listing first and reading only the files that matter keeps the 5MB string limit in view. For the query methods used on that result, see the GlideRecord API guide.

Write new attachments to a record

Three write methods cover the common cases. The write method takes a GlideRecord that is already loaded, a file name, a MIME content type and a string of content. It returns the sys_id of the new attachment, or null if the attachment was not added, so check the return value before the next step relies on it.

The content type is a MIME value such as text/csv or image/png. It is stored in the Content type field of the Attachment table, so the value you set is the value a later reader sees.

The writeBase64 method inserts an attachment from base64 encoded content. Use it when the source already arrives encoded, for example from an integration payload. The writeContentStream method inserts an attachment from a stream and returns the sys_id of the created record. It suits copying one attachment onto a record on another table.

One way to write a copy reads the stream of an existing sys_attachment row and writes that stream onto the target record. Confirm the target record exists before the write, since the attachment has to land on a record that is there.

Copy and delete attachments between records

The copy method takes a source table, a source sys_id, a target table and a target sys_id. It copies the attachments from the source record to the target record and returns an array of the new sys_ids.

The copy method takes no filter. It copies all attachments on the source record. If a script needs one file on the target and not the rest, write that file with write or writeContentStream instead.

The deleteAttachment method takes an attachment sys_id and deletes that attachment. It returns nothing, so query the Attachment table to confirm the removal when a later step depends on it.

Read large text line by line with GlideTextReader

GlideTextReader wraps a GlideScriptableInputStream and returns one line at a time. Its readLine method returns a line without the carriage return and returns null when no content remains, which gives the loop a clean stopping condition. Because it reads from a stream, it is not subject to the 5MB attachment size limit.

var is = new GlideSysAttachment().getContentStream(attachmentSysId);
var reader = new GlideTextReader(is);
var ln;
while ((ln = reader.readLine()) != null) {
  gs.info(ln);
}

The getEncoding method returns the character encoding of the stream. Check it when the file came from an outside system, because a mismatch between the encoding and the text you expect produces garbled output.

Parse Excel workbooks with GlideExcelParser

GlideExcelParser reads .xlsx workbooks. GlideExcelParser works in both global and scoped scripts. You create it with the sn_impex namespace, so the constructor call reads sn_impex.GlideExcelParser.

A basic parse follows a fixed order. Parse the stream, read the column headers, then move through the rows with next and getRow. The getRow method returns an object whose property names are the headers, so you read each cell by its header name rather than by position.

var parser = new sn_impex.GlideExcelParser();
var attachmentStream = new GlideSysAttachment().getContentStream(attachmentSysId);
parser.parse(attachmentStream);
var headers = parser.getColumnHeaders();
while (parser.next()) {
  var row = parser.getRow();
  gs.info(row[headers[0]]);
}
parser.close();

Call close when the work is done to release the stream and the document. For the wider concept behind spreadsheet loads, see the import set explainer.

Workbooks with several sheets need more setup. Call setSource with the stream when you intend to parse the same document more than once. The getSheetNames method returns the worksheet names, so loop through them and call setSheetName for each one.

Three settings shape the output. The setHeaderRowNumber method tells the parser which row holds the headers, which helps when a workbook has a title block above the table. The setNullToEmpty method, set to true, returns an empty value in place of null for cells that are not present. The parse method returns a truthy result on success. When it fails, getErrorMessage returns the reason, so check the result before reading rows.

The getTableInfo method returns column types and maximum character lengths from a spreadsheet or CSV attachment. It is restricted to scoped applications.

Return attachment content from a scripted REST API

RESTAPIResponseStream writes to the response of a scripted REST API. The object is created automatically inside scripted REST resource scripts and runs in the sn_ws namespace, so you do not instantiate it yourself.

Two ordering rules apply. Set the content type and the status code before you write anything, because the response fails if you write first. Once you call writeStream or writeString, neither value can change. The writeStream method sends an input stream, such as an attachment stream, straight to the caller. The writeString method sends a string, which suits JSON you build in the script. When the stream comes from a third-party service, the script author is responsible for fetching it. For the design side of scripted endpoints, see the REST and SOAP integrations hub and the scripted REST API design contracts article.

response.setContentType('application/json');
response.setStatus(200);
var writer = response.getStreamWriter();
writer.writeString(JSON.stringify({ id: 1234, name: 'user' }));

Take care with the sample attachment scripts

ServiceNow publishes a set of useful attachment scripts. They are provided as-is, ServiceNow Support does not cover them, and they need thorough testing before use.

The duplicate-removal sample queries the sys_attachment table, orders the rows by table sys_id and then by creation date, and compares each row with the one before it. A match on table sys_id and file name marks a duplicate, which the script deletes. Run it in a business rule, a scheduled job or a background script, and test it against a copy of the data first, because deletion is hard to undo. For the business rule and scheduled job options named here, see the business rule explainer and the scheduled job explainer.

Frequently asked questions

Which method should I use for a file of around 20MB?

Use getContentStream and pass the stream to a consumer such as GlideTextReader or GlideExcelParser. The string methods top out at 5MB, while a stream read line by line is not subject to that limit.

Why does getContent return undefined in my global script?

The method is scoped. Global scripts should read the content through getContentStream and pass the stream to a reader.

Can copy move a single attachment from a record?

No. The copy method takes no filter and copies all attachments on the source record. To place a single file on the target, write that file with write or writeContentStream.

Which parser reads an Excel workbook in a global script?

Use sn_impex.GlideExcelParser, which works in both global and scoped scripts. Its getTableInfo method is the exception, since it is restricted to scoped applications.