Monday, 15 February 2016

ServiceNow Table Attachments - Reading Data from attachments

ServiceNow provides us with a great feature of adding attachments to table records. And everything here is practically a table. So everything can have attachments. We need to read the data in the files that are attached at many times. Here I am sharing a code snippet that can help you achieve the same.

                recordId = 'myRecordSysId'; //sys_id of the record that contains attachment
                var attGr = new GlideRecord('sys_attachment');  //go to sys_attachment table
    attGr.addQuery('table_name', 'myTableBName'); //specify your table name as second parameter
attGr.addQuery('table_sys_id', recordId);
attGr.orderByDesc('sys_updated_on'); //helps to retrieve the latest attachment to record
attGr.query();
if(attGr.next())
       {
var gsu = (typeof GlideStringUtil != 'undefined') ? (GlideStringUtil) : (Packages.com.glide.util.StringUtil); //few versions support the first one, other supports second
var gsa = (typeof GlideSysAttachment != 'undefined') ? (new GlideSysAttachment()) : (new Packages.com.glide.ui.SysAttachment());
var attachmentData = gsa.getBytes(attGr);
var attachment = String(Packages.java.lang.String(attachmentData));
gs.print(attachment); //the data in the file will be printed as String

This code works practically with all the versions of ServiceNow be it Eureka or Geneva, still if it doesn't work somehow for you please drop a comment below. :)

Queries are most welcome... :)

12 comments:

  1. This code is working fine for .text file , but its not working for excel file. Please help

    ReplyDelete


  2. well done the blog is great and it is about ServiceNow Table Attachments - Reading Data from attachments it is useful for students and servicenow Developers for more updates on servicenow ServiceNow Online training

    ReplyDelete
  3. well done the blog is great and it is about ServiceNow Table Attachments - Reading Data from attachmentsit is useful for students and servicenow Developers for more updates on servicenow ServiceNow Online training

    ReplyDelete
  4. Awesome post dear. I enjoyed reading it. For servicenow online training click on link servicenow real time training

    ReplyDelete
  5. Does this work for images and pdf documents?

    ReplyDelete
  6. Cool and I have a neat present: How To Renovate House Exterior exterior home remodel

    ReplyDelete