Base64 is returning null in scoped application REST API explorer

APRAJITAPAL
Kilo Contributor

I have scoped application. On Request I am attaching pdf file. While using GET https method in scripted REST API, I am getting null in Base64. However I am getting file name, content type, sys_id. Using below code-

 

_readAttachmentAsBase64: function(attachmentSysId) {
        try {
            /*var ais = new GlideSysAttachmentInputStream(String(attachmentSysId));
            var baos = new Packages.java.io.ByteArrayOutputStream();
            ais.writeTo(baos);
            var bytes = baos.toByteArray();
            baos.close();
            return this._b64Encode(bytes);
        } catch (e) {
            gs.error('GAD ERR: base64 read failed for attachment ' + attachmentSysId + ': ' + e.message);
            return null;
        }*/
        var gsa = new GlideSysAttachment();
        var inputStream = gsa.getContentStream(attachmentSysId);
        if(!inputStream){
            gs.error("No stream for attachment:"+attachmentSysId)
    return null;
        }
        var baos = new Packages.java.io.ByteArrayOutputStream();
        var buffer = Packages.java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 4096);
        var bytesRead;
        while((bytesRead = inputStream.read(buffer)) != -1){
            baos.write(buffer,0,bytesRead);
        }var bytes = baos.toByteArray();
        var base64 = GlideStringUtil.base64Encode(bytes);
        return base64;
        } catch (e){
            gs.error("STREAM ERROR:"+e.message);
            return null;
        }
    },
2 REPLIES 2

pr8172510
Kilo Guru

 

Hi @APRAJITAPAL

This issue is because you are using Packages.* in a scoped application, which is restricted and results in null / failure.

Instead of using input streams manually, use the OOTB API:

 

 
var gsa = new GlideSysAttachment();
var base64 = gsa.getContentBase64(attachmentSysId);
return base64;
 

This works in scoped apps and avoids stream handling issues.


If getContentBase64() still returns null, then check:

  • Attachment exists and sys_id is correct
  • Attachment is accessible in current scope (ACLs)

Ankur Bawiskar
Tera Patron

@APRAJITAPAL 

are you in scoped app or global scope?

Regards,
Ankur
Certified Technical Architect  ||  10x ServiceNow MVP  ||  ServiceNow Community Leader