We're reclaiming inactive PDIs to keep them available for active builders. Learn what's changing, who's affected, and how to protect your work. Read More

User script to add attachment to data source

Aliuvancouver
Tera Contributor

I use a MID Server script include to edit a file, then add to a data source. It runs and no error occurred. However, I don't see the attachment added on the data source. Any idea why? Here is my script:

 

var header = ("account" + "\n");

this.log("Trying to download file.");
var RemoteFileName = "STATUS_FILE.csv";
sftp.get(RemoteFileName, output);

//delete the existing attachments
this.log("Deleting existing attachments.");
var gr = new GlideRecord('sys_data_source');
gr.addQuery('sys_id', this.dataSourceID);
gr.query();
 if (gr.next()) {
 attachment.deleteAll(gr);
 }
if (gr.next()) {
//set up input stream
this.log("Setting up input stream. ");
var strOutput = (header + Packages.java.lang.String(output));
this.log("output= " + strOutput);
var base64EncodeString = this.StringUtil.base64Encode(strOutput);
var input = this.StringUtil.base64DecodeAsBytes(base64EncodeString);

//set up the attachment
var attachment = Packages.com.glide.ui.SysAttachment();
attachment.setTableName('sys_data_source'); //table name of the record this is being attached to
attachment.setTableSysID(this.dataSourceID); //sys_id of the data source record this is being attached to
attachment.setFileName(this.filename); //the name of the file as it should appear after it's uploaded
attachment.setContentType(this.contentType);

//save the new attachment
this.log("Saving new attachment."); //attach the attachment.
// var attachment = new Attachment();
// var attachment_sys_id = attachment.write("sys_data_source", this.dataSourceID, "1111.csv", "test/csv", decodedData);
attachment.setInputStream(input);
attachment.write();

}

} catch (e) {
this.log("File download failed. Disconnecting. error: " + e);
return false;
}
sftp.quit();
ssh.disconnect();

return true;
},


log: function(data) {
ms.log(data);
},

2 REPLIES 2

Liz26
Kilo Contributor

Hi, did you manage to achieve this? I have a similar requirement and need help please

Here is a KB article https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB0817437