Help
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Getting contents of an attachment

MatthewPearson
Tera Contributor

I need to get the contents of an attachment and have tried using the following in a background script (for testing purposes only):

var sa = new GlideSysAttachment();
var binData = sa.getBytes('incident', '892a8ba0a400f000e9ece890a93b7172');
gs.print(binData);

However the response I get back is always something like:
[B@bdbc52
Which doesn't look at all like the file I have attached. I've tried a few different file attachment types and attached them to a few different types of record.
I have also tried passing a only GlideRecord on the sys_attachment table to getBytes and I get the same answer.
Once I have the contents of the file, I'd like to modify the content and create a new attachment (on a different record) with my modified content.
It looks like all of this should be possible, but I just can't get past the garbage I get out of getBytes.
I'm on Calgary Patch 2 Hotfix 5.

Thanks in advance

20 REPLIES 20

Jacob_Andersen
ServiceNow Employee
ServiceNow Employee

Here is some code that should help you. You're almost there, you just need to convert the byte array to a string:



StringUtil = GlideStringUtil;
sa = new GlideSysAttachment();

var bytesContent = sa.getBytes('incident', '892a8ba0a400f000e9ece890a93b7172');
var strData = Packages.java.lang.String(bytesContent);


I've got an attachment on the ECC Queue table because the output from a Command is too large.
I've tried _everything_ to get the contents of that attachment, but nothing other than the [B@234987 ever seems to come out:

var bytesContent = sa.getBytes("ecc_queue", "1fa73b5c3ca51100e53a5f77ec11c453");
gs.log("Your thing looks like: " + bytesContent);
var strData = Packages.java.lang.String(bytesContent);
var binData = GlideStringUtil.base64DecodeAsBytes(bytesContent);
gs.log("Found: " + binData);

gives:
*** Script: Your thing looks like: [B@143e157
*** Script: Found: [B@2d261d

Any thoughts? It's Calgary...


andrew_kincaid
ServiceNow Employee
ServiceNow Employee

I believe your strData is already in the format you need - assuming the attachment is a text file. I don't think you need to base64 decode. Also, I recommend you convert to a JavaScript string so you don't rely on Rhino's automatic string conversion.



var bytesContent = sa.getBytes("ecc_queue", "1fa73b5c3ca51100e53a5f77ec11c453");
gs.log("Your thing looks like: " + bytesContent);
var strData = String(Packages.java.lang.String(bytesContent));
gs.log("Found: " + strData);



If that doesn't work, let me know.


You're right, no need to Base64 decode, but it does seem to be necessary to go to the JavaScript String from the Java String,
i.e.:
var strData = String(Packages.java.lang.String(bytesContent));
works!

but:
var strData = String(bytesContent);
or:
var strData = Packages.java.lang.String(bytesContent)

Do not!