
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-17-2023 08:42 PM
Hi,
I am using a REST API from servicenow (/api/now/attachment/{sys_id}/file) to get the binary file of an attachment (code below)
var rest = new sn_ws.RESTMessageV2();
rest.setEndpoint('https://xxxxxxxxxx.service-now.com/api/now/attachment/6f20c5fe1bbe6d10e641eb5be54212/file');
rest.setHttpMethod('get');
rest.setRequestHeader("Accept",'*/*');
rest.setBasicAuth("user","password");
var response = rest.execute();
var obj = response.getBody();
gs.info(obj); /* obj is the binary representation of the attachment */
Is there a way to convert the binary file (obj) to base64 ? I tried using GlideStringUtil.base64Encode(obj) but it seems not correct. Can you help me ?
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-17-2023 10:29 PM
Hi @Lucas Romani1 ,
You can use the GlideStringUtil.base64Encode() method to convert the binary file to Base64 in ServiceNow. Here's an updated version of the code using GlideStringUtil.base64Encode():
var rest = new sn_ws.RESTMessageV2();
rest.setEndpoint('https://xxxxxxxxxx.service-now.com/api/now/attachment/6f20c5fe1bbe6d10e641eb5be54212/file');
rest.setHttpMethod('get');
rest.setRequestHeader("Accept", '*/*');
rest.setBasicAuth("user", "password");
var response = rest.execute();
var obj = response.getBody(); // obj is the binary representation of the attachment
var base64String = GlideStringUtil.base64Encode(obj);
gs.info(base64String); // base64String is the Base64 representation of the binary file
For converting large files to base64encode string, you can refer below script:
var StringUtil = new GlideStringUtil();
var gsis = GlideSysAttachmentInputStream(gr.sys_id.toString());
var ba = new Packages.java.io.ByteArrayOutputStream();
gsis.writeTo(ba);
baos.close();
var base64EncodedData = StringUtil.base64Encode(ba.toByteArray());
If my response was helpful in resolving the issue, please consider accepting it as a solution by clicking on the ✅Accept solution button and giving it a thumbs up 👍. This will benefit others who may have a similar question in the future.
Thank you!
Ratnakar
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-31-2024 04:18 AM
Hi @SrikanthD1G ,
I have a similar requirement where I have to read the response (binary data) and attach the same in the incident record. Did you find the solution for your query ?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-18-2023 05:28 AM
what's your requirement?
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader