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

@Reena Kumari3 

that's what I am saying. why to parse?

you get base64encoded data from 3rd party just use the script I shared and it will attach the file using OOB logic and you need not worry.

Did you try that script? if yes then what's the issue?

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

@Ankur Bawiskar 

I tried the above script provided by you. It didn't work.

Regards

Reena

@Reena Kumari3 

You are not sharing the complete script.

The script I shared will work fine provided these are correct -> base64 data, file name, content type, table name, record sysId

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

Hi Ankur,

I have tried the below script and it's giving the output. Please let me know is it a correct approach or not?

var attachment = new GlideSysAttachment();
var rec = new GlideRecord('incident');

rec.get('sys_id');//sys id of a record where to attach the file

var filename = 'abc1.txt';

var contentType ='text/csv'

var my_string = 'SEkgSSBhbSByZWVucw0K';

var str2 = GlideStringUtil.base64Decode(my_string);

var agr = attachment.write( rec,filename,contentType,str2);

gs.info(+agr);

Thanks

Reena Kumari

@Ankur Bawiskar 

I tried your shared code like this, I am sharing my script that I modified .Please help me out where I am missing anything.

var eccGr = new GlideRecord('ecc_queue');
eccGr.initialize();
eccGr.setValue('agent', 'AttachmentCreator');
eccGr.setValue('topic', 'AttachmentCreator');
eccGr.setValue('name', testing + ':' + pdf); // give here the file name and content type
eccGr.setValue('source', incident + ':' + e8caedcbc0a80164017df472f39eaed1); // give here the table name and record sysId to which you need to attach
eccGr.setValue('payload', iVBORw0KGgoAAAANSUhE);//my string content
eccGr.insert();

Thanks

Reena