Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

Create .txt file in sys_attachment from data stored in a table

jogmen
Giga Contributor

Has anyone programatically created a text file attachment from data stored in a field in a ServiceNow table from a business rule?

I am essentially trying to emulate the behavior in the Attachment Note workflow activity. I need to create an attachment, but on a table that doesn't support that activity - so I want to include a Run Script activity with code that will allow me to create an attachment on the record.

I was thinking something like:

var file = new GlideRecord("sys_attachment");
file.file_name = "testname.txt";
file.CONTENTS = VARIABLECONTENT;
var sysID = rdp_file.insert();

But am not sure how to actually funnel the text from my variable into the content for the attachment record.

Any help would be appreciated.

9 REPLIES 9

jogmen
Giga Contributor

For those that are interested, following is my solution:

insertAttachment(); //note, you need to wrap the StringUtil Package call (below) inside a function or this will error

function insertAttachment() {

var attachmentName = 'text.txt:plain/text';
var attachmentSource = 'cmdb_ci_ec2_instance:' + current.sys_id; //inserting this onto a specific EC2 VM instance - you can target your desired table accordingly

var attachmentPayload = 'some string';
var StringUtil = Packages.com.glide.util.StringUtil;
var encodedPayload = StringUtil.base64Encode(attachmentPayload);

var rec = new GlideRecord('ecc_queue');
rec.initialize();
rec.agent = "AttachmentCreator";
rec.topic = "AttachmentCreator";
rec.name = attachmentName;
rec.source = attachmentSource;
rec.payload = encodedPayload;

var flag = rec.insert();
}


Just wanted to thank you for this ... Saved my day


So, this is a bit of an old thread, but super helpful.   You can also do this without using the ecc_queue as well.


insertAttachment();



function insertAttachment() {


  var attachmentPayload = 'some text';



  i = new GlideRecord('incident')


  i.get('bdb5c2a3dbc4ee0043563bc0cf961981')



  var sa = new GlideSysAttachment();


  var attachmentId = sa.write(i, 'test.txt', 'plain/text', attachmentPayload);


  if(attachmentId)


            return true;


  else


            return false;


}


Nice one Daniel!!