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

9 REPLIES 9

Hello Hardik,

 

Please let me know Maximum size limit for file to convert to base64?. Because i tried with 3MB file.

var encData = GlideStringUtil.base64Encode(binData);

The "encdata" variable printing empty. Please help me with the file size.

 

Thank you

Just in case anyone looks at this post again. The second line should be to create the attachment now.

var attachment = new GlideSysAttachment();

Thanks again for your answer it was very helpful to us!

 

Souvik Chakrabo
Tera Contributor

Hello all,

writeBase64 didn't work for me, it was returning "undefined".

But, got 2 ways to do this.

 

1. Using ECC QUEUE "AttachmentCreator" agent. 

Create a Script Include with the Code Below:

var attCreator = new GlideRecord('ecc_queue');
attCreator.agent = "AttachmentCreator";
attCreator.topic = "AttachmentCreator";
attCreator.name = name + ":" + contentType; //For Example: Test.pdf:application/pdf 
attCreator.source = record.getTableName()+":"+record.sys_id; // Record Table name and sys_id of the perticular record
attCreator.payload = data; //base64 Content of the file
attCreator.insert();

And Call the script include function wherever needed.

 

2. Using GlideStringUtil.base64DecodeAsBytes(base64File):

var base64File= "JA....XX" //The huge base64Encoded string

var DecodedBytes = GlideStringUtil.base64DecodeAsBytes(base64File); //Decodes the base64Encoded Data in Bytes.


var attach = new GlideSysAttachment();

attach.write(gr_record, file_name, contentType, DecodedBytes );

//Accepts 4 parameters: 1. GlideRecord object, Filename(Eg: Test.pdf), Content Type(Eg: application/pdf), DecodedBytes

 

Both the ways worked for me. 🙂  

hello Souvik, can you tell me how you did this?
var base64File= "JA....XX" what is this ?

 

 

actually i tried with ecc quue still id didnt work ,using script


Please accept the solution /mark this response as correct or helpful if it assisted you with your question.




Regards,
Animesh

Hi @AnimeshP_96

 

var base64File= "JA....XX" what is this ?

 

-- This is the base64 of the attachment that you will get from the integration or you convert the blob to base64 and then follow the steps mentioned above in the solution to attach it to a record in servicenow.

 

Let me know if you face any issues in this.