- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-14-2025 07:01 AM
Hi Everyone,
I’m working on a use case where I need to read the content of an attachment file (like a .txt or .json file) that is attached to a Knowledge Article.
I tried the following script, file name is coming correctly but the file content is empty. Can someone please guide me on the correct way to read the content of the attached file?
Here is the code I’ve used so far:
JSON result [ {"FileName": "cmdb_ci_data.txt", "FileContent":""}]
Regards
Deepak Tomar
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-14-2025 07:09 AM
getContentStream() required attachment sysId, but you are passing the GlideRecord object
I updated below, can you try this?
var attachments = [];
var attachmentGR = new GlideRecord('sys_attachment');
attachmentGR.addQuery('table_name', 'kb_knowledge');
attachmentGR.addQuery('table_sys_id', '<sys_id of kb article>'); // Replace with actual sys_id
attachmentGR.query();
while (attachmentGR.next()) {
var fileName = attachmentGR.file_name.toString();
// Pass the sys_id string, not the GlideRecord, to getContentStream()
var sa = new GlideSysAttachment();
var stream = sa.getContentStream(attachmentGR.sys_id.toString());
if (stream && (fileName.endsWith('.txt') || fileName.endsWith('.json') || fileName.endsWith('.csv'))) {
var reader = new GlideTextReader(stream);
var content = '';
var line;
while ((line = reader.readLine()) !== null) {
content += line + '\n';
}
attachments.push({
FileName: fileName,
FileContent: content
});
}
}
gs.info('JSON result: ' + JSON.stringify(attachments));
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-14-2025 07:42 AM
Glad to know.
You cannot print doc, docx, pdf file etc as those are not in plain text and not supported by ServiceNow to read the content.
You can only read txt, csv files etc
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-14-2025 07:42 AM
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-14-2025 07:42 AM