How to convert binary file into Base64 string

Abhinaw Tiwari
Kilo Explorer

Hi All, 

I am pretty new to Service Now development. I want to convert the binary file into a Base64 string. I am downloading File usingAttachment API. Can anyone please suggest how to do it. Below I am mentioning my code to download the binary file from Attachment API.

var fileUrl = 'https://instance-url/api/now/attachment/'+attachment_id+'/file';
var request = new sn_ws.RESTMessageV2();
request.setEndpoint(fileUrl);
request.setHttpMethod('GET');

//Eg. UserName="admin", Password="admin" for this code sample.
var user = 'admin';
var password = 'admin';

request.setBasicAuth(user,password);
request.setRequestHeader("Accept","*/*");

var attchementResponse = request.execute();
var attachmentResponseBody = attchementResponse.getBody();

So 'attachmentResponseBody ' is my binary file which I want to convert into Base64 string.

 

Thanks in advance!!

2 REPLIES 2

Raj68
Mega Guru

Hi Abhi,

hope below code will help you to convert binary to base64 :

Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);

NOTE: Mark correct or helpful if it helps you.

Warm Regards,

Raj patel

 

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Abhinaw,

I don't think directly you can do.

From where you are calling this endpoint?

Regards

Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader