Convert Attachment to base64 encoded content and vice versa

Reena Kumari3
Tera Contributor

 Hi Team,

My first requirement is to get the attachment in base64encoded content, I just achieved this with the below script and output  is also given below:-

 

var tableName = 'incident';
var recordID = 'ca644b5997261110e8fe39000153af00';
gs.print(getAttachmentContentsAsString(tableName, recordID));
function getAttachmentContentsAsString(tableName, recordID) {
	var gsa = new GlideSysAttachment();
	var bytesInFile = gsa.getBytes(tableName, recordID);
	var base64string = GlideStringUtil.base64Encode(bytesInFile);
	gs.info('Attachment content base64 encoded: ' +base64string);
}



ReenaKumari3_0-1666092760188.png

 

My Second requirement is to convert base64 content to an attachment and  linked to an incident .

@Ankur Bawiskar  @Mark Roethof 

10 REPLIES 10

Ankur Bawiskar
Tera Patron
Tera Patron

@Reena Kumari3 

you can use this function to decode and add to file i.e. use SOAP Attachment creator

Something like this

var tableName = 'incident';
var recordID = 'ca644b5997261110e8fe39000153af00';
gs.print(getAttachmentContentsAsString(tableName, recordID));
function getAttachmentContentsAsString(tableName, recordID) {
var gsa = new GlideSysAttachment();
var bytesInFile = gsa.getBytes(tableName, recordID);
var base64string = GlideStringUtil.base64Encode(bytesInFile);
gs.info('Attachment content base64 encoded: ' +base64string);

var eccGr = new GlideRecord('ecc_queue');
eccGr.initialize();
eccGr.setValue('agent', 'AttachmentCreator');
eccGr.setValue('topic', 'AttachmentCreator');
eccGr.setValue('name', fileName + ':' + contentType); // give here the file name and content type
eccGr.setValue('source', tableName + ':' + tableSysId); // give here the table name and record sysId to which you need to attach
eccGr.setValue('payload', base64string);
eccGr.insert();
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

 

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

@Ankur Bawiskar 

 Thanks for your quick response and I went through your response, but my requirement is  that I want to parse the base64 content and add it to incident.

 

Regards

Reena

@Reena Kumari3 

what do you mean by parse?

If you have base64 data then there is OOB API why you want to parse?

 

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

@Ankur Bawiskar 

Actually,we are doing soap integration and we are receiving attachment content in base64 encoded  format and we want to convert it to normal content and attach it to incident record.

Thanks

Reena