How can I create an attachment from script?

Joey Wan Kenobi
Tera Guru

Does SN offer any API to create an attachment?  I've used the following:

 

var gsa = new GlideSysAttachment(); var attachmentId = sa.write(gr, "fileName.txt", 'text/plain', "some data");

 

This works fine for creating text files. It doesn't work when trying to create a pdf, doc or docx file. Is there a way to do so?

22 REPLIES 22

Community Alums
Not applicable

Hi jarodm,

is there any possible to attach the single pdf  on multiple records through Attachment API

Joey Wan Kenobi
Tera Guru

Has anyone used the Attachment Creator API within SN script to create an attachment from scratch?


OR


I've also seen someone say they created an attachment by inserting a record into the ecc_queue. I did not find this to work either.


var eccGr = new GlideRecord('ecc_queue');


eccGr.initialize();


eccGr.setValue('agent', 'AttachmentCreator');


eccGr.setValue('topic', 'AttachmentCreator');


eccGr.setValue('name', fileName+':'+contentType);


eccGr.setValue('source', tableName+':'+tableSysId);


eccGr.setValue('payload', content);


eccGr.insert();


I've seen that method used before (Generate Attachments in ServiceNow via REST | John Andersen) , but haven't done it myself.


hi,


I to have the same issue ,did you find any solutions for it.


I have tried using the ecc_queue but it works on dev instance but not on test instance can you help what must be the issue.


I looked around I found this code to work for me. This is for attaching an image file, but should work for other attachments as well. It should be noted that ServiceNow does break up the attachment data into 4k chunks within the sys_attachment_doc table. Anything too big like high-resolution images will slow down upload and rendering time.


Another work around I found was replacing the attachment itself. The Attachment API didn't work out for me, so I instead deleted the 'old' attachment and ran the code snippet for attaching the file.


Not the cleanest work around but hopefully this helps or point you in the right direction!




var CreateAttachment = Class.create();



CreateAttachment.prototype = {


        initialize: function(record,name,contentType, data) {


                  var attCreator = new GlideRecord('ecc_queue');


                  attCreator.agent = "AttachmentCreator";


                  attCreator.topic = "AttachmentCreator";


                  attCreator.name =   "image" + ":" + contentType;


                  attCreator.source = record.getTableName()+":"+record.sys_id;


                  attCreator.payload = data;


                  attCreator.insert();


        },


        type: 'CreateAttachment'


};



var targetTable= new GlideRecord('x_target_table');


targetTable.addActiveQuery();


targetTable.addQuery('sys_id','=',input.sys_id);


targetTable.query();


while(targetTable.next()){


        new CreateAttachment(targetTable,"MyPhoto.jpg","image/jpeg",input.image);


}