How to send binary data with multipart from ServiceNow to Third Party applications (Box, Jira, etc…)
Most REST API’s are pretty straight forward, however handling binary data in ServiceNow is more complicated.
Note: this is mainly meant to provide examples of multipart building.
There is a great SN share project that implements how to send binary data through a clever workaround HERE, but there is a missing explanation how to add your binary data properly.
So first, how does this workaround actually work?
- Grab the attachment you want to send
- Call internal SN REST API that has access to response.getStreamWriter() object
- Create a new file using getStreamWriter() and add all boundaries and multipart request specific data parameters
- Save response body as an attachment – new binary file will be created that will hold attachment data with multipart parameters in clear text. If you opened the file with notepad, this is what you would see:

5. Send the attachment with setRequestBodyFromAttachment.
6. Send the attachment to third party API.
7. Delete the attachment created just for this.
In this example I will show you how to send binary data to Box and Jira.
JIRA is simpler, as it only requires single multipart piece. This is how you build getStreamWriter() object:
var writer = response.getStreamWriter();
writer.writeString("--" + boundaryValue + "\r\n"); //boundaries are read by the server
writer.writeString('Content-Disposition: form-data; name="file"; filename="' + fileName + '"\r\n');
writer.writeString('Content-Type: ' + contentType +'\r\n');
writer.writeString('\r\n'); // need to leave additional line empty before binary data
writer.writeStream(inputStream); // this is actual binary data
writer.writeString("\r\n--" + boundaryValue + "--\r\n");
BOX requires multiple multipart parameters:

This translates to this in SN:
var writer = response.getStreamWriter();
writer.writeString("--" + boundaryValue + "\r\n");
writer.writeString('Content-Disposition: form-data; name="attributes"\r\n');
writer.writeString('\r\n');
writer.writeString('{"name":"' + fileName + '","parent":{"id":"11223334444"}}\r\n'); //this is just text data, could be binary
writer.writeString("--" + boundaryValue + "\r\n"); // note multiple boundaries for each File attribute
writer.writeString('Content-Disposition: form-data; name="file"; filename="' + fileName + '"\r\n');
writer.writeString('Content-Type: ' + contentType +'\r\n');
writer.writeString('\r\n');
writer.writeStream(inputStream);
writer.writeString("\r\n--" + boundaryValue + "--\r\n");
That’s it!
Note: this can also be done using GlideSysAttachment().write(), however above mentioned way is documented and supported by ServiceNow, going GlideSysAttachment().write() route you have to use undocumented getBytes() method which could end up risky down the years.
https://servicenowthink.wordpress.com/2020/04/13/how-to-send-binary-data-with-multipart-from-servicenow-to-third-party-applications-for-free/