Reading the content of attachment files

sajerond
Tera Contributor

I'm trying to read the data from the attachment and load the data to an html field.  I've been able to get it to work.  But in our case, we could have up to three attachments for three different html fields.  This getBytes() only identifies the record id and not the attachment sysid so I cannot retrieve the individual attachments.  It will pull up any of the attachments data and load the same one to all three.  Any ideas to get to the attachment record level?

 

var sysAddress = current.sys_id;
var gsa = new GlideSysAttachment();
var bytesInFile = gsa.getBytes('incident',sysAddress);
var originalContentsInFile = Packages.java.lang.String(bytesInFile); // originalContentsInFile
originalContentsInFile = String(originalContentsInFile);
current.u_excluded_adddress = originalContentsInFile;

5 REPLIES 5

Brad Bowman
Kilo Patron
Kilo Patron

You can query the sys_attachment table to retrieve each record, then getContentStream and read it:

var att = new GlideRecord('sys_attachment');
att.addQuery('table_sys_id', current.sys_id);
att.orderByDesc('sys_created_on');
att.query();
while (att.next()) {
    var attach = new GlideSysAttachment().getContentStream(att.sys_id.toString());
    var reader = new GlideTextReader(attach);
    var ln = ' ';
    while ((ln = reader.readLine()) != null) {
        gs.info(ln);
    }
}

https://docs.servicenow.com/bundle/vancouver-api-reference/page/app-store/dev_portal/API_reference/G... 

 

https://docs.servicenow.com/bundle/vancouver-api-reference/page/app-store/dev_portal/API_reference/G... 

Brad,  This is helpful and works to a point.  It looks like I can separate the files using this but in this case, it's a csv file with multiple rows.  It only retrieves the last row, not the entire dataset

jdestef
Tera Contributor

Just concatenate the lines together as you read them. 

 

var fulldata = "";
var line;

while ((line=reader.readLine())!==null) {
    fulldata = fulldata + line;
}

gs.log(fulldata);

Hi @Brad Bowman  ,
It is working for .txt file types, But it is not working for .doc and .pdf is there any solution for those file types.