The Now Platform® Washington DC release is live. Watch now!

Help
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Decoding base64 encoded file and writing it to sys_attachment table

Souvik Chakrabo
Tera Contributor

Hi,

I am integrating ServiceNOW with a 3rd party application where the 3rd party application is sending a file in my custom servicenow endpoint (Scripted REST API). The file is base64 encoded and I need to decode that base64 to get the document out of it and insert it in sys_attachment table.

Need suggestions for implementing this.

 

Thanks in advance

7 REPLIES 7

dvp
Mega Sage
Mega Sage

I have one question, while encoding any attachment to base64 in ServiceNOW, we use GlideSysAttachment().getBytes('sys-attachment-record') and then we encode the bytes to base64; but for writing any base64 encoded attachment to sys_attachment, should we pass the base64 encoded string that comes from the 3rd party application as the content or we should use some other way?

If content is base encoded use writeBase64 method

Hardik Benani
Kilo Sage
Kilo Sage

You can also try below for processing incoming attachments:

var StringUtil = new GlideStringUtil();
var attachment = new Attachment();
if (JSUtil.notNil(source.u_attachment1_name))
attachment.write('incident',target.sys_id, source.u_attachment1_name, '', StringUtil.base64DecodeAsBytes(source.u_attachment1));

for outgoing you can use:

var max_size = 2000000; //2 MB
var cgiAttch = new GlideRecord('sys_attachment');
cgiAttch.addQuery('table_sys_id',current.sys_id);
cgiAttch.setLimit(1);
cgiAttch.query();
while(cgiAttch.next()){
var sa = new GlideSysAttachment();
var binData = sa.getBytes(cgiAttch);
var size = parseInt(cgiAttch.size_bytes);
if(size > max_size) {
gs.addInfoMessage("Ignoring sending of attachment to remedy, size exceeds 2MB");
gs.log('Ignoring sending of attachment due to size exceeds 2MB');
//current.setAbortAction(true);
} else {
var encData = GlideStringUtil.base64Encode(binData);
s.setStringParameter('Attachment1Name', cgiAttch.file_name);
s.setStringParameter('Attachment1Data', encData);
s.setStringParameter('Attachment1Size', '');
}
}

 

Note: If I have answered your question, please mark my response as correct so that others with the same question in the future can find it quickly and that it gets removed from the Unanswered list.