Richard Dunmow
ServiceNow Employee
ServiceNow Employee

Retrieving the Image and displaying on the widget.

Now that the image has been saved to the database, the next problem is retrieval and sending back to the client for display.

The issue starts when you try to read the image. Normally you would just retrieve the image data from the glide record and pass that to the client script using some code like this

data.info = [];
var gr = new GlideRecord('x_snc_attendee');

//Possibly add some query constructs here
// gr.addQuery("sys_id",input.data.sys_id);

gr.query();

if (gr.next()){
    data.info = {
        sys_id: gr.getValue("sys_id"),
        name: gr.getValue("full_name"),
        image: gr.getValue("image")
    }
}

The data that is passed back in the data.info.image variable is actually the filename. So it would return something like "1abdf456ag321.iix", if my service now url was "https://mysystem.service-now.com/" I would simply add the end and I could get my picture back.

Displaying the picture would be simple enough, we can use the <img> HTML tag like before, which would be

 <img src="{{ c.data.info.image }}" width="100%">

This only works when you're logged in, for the widget I am building this would not work as the user is not logged in, so we have to find a different way to display the image.

Extracting the Base64 image data from the system.

In order to pass the image to the client, we need to actually extract the image from the attachment table and provide the data directly to the client to display. Like we did when we sent the Base64 image data to the server, but in reverse.

The code extract below extends the original code and adds the extract needed to get the actual image from the sys_attachment table and convert it to base64.

data.info = [];
var gr = new GlideRecord('x_snc_attendee');

//Possibly add some query constructs here
// gr.addQuery("sys_id",input.data.sys_id);

gr.query();

if (gr.next()){

    // We need the GlideAttachment object to convert the data to Base64
    var ga = new GlideSysAttachment();
    
    //Open the Glide Attachment record
    var attachmentGr = new GlideRecord('sys_attachment');
    
    attachmentGr.addQuery('table_name', 'x_snc_attendee');
    attachmentGr.addQuery('table_sys_id', gr.getValue("sys_id"));
    attachmentGr.addQuery('file_name', 'image');
    attachmentGr.setLimit(1);
    attachmentGr.query();
    attachmentGr.next();

    data.info = {
        sys_id: gr.getValue("sys_id"),
        name: gr.getValue("full_name"),
        image: "data:" + attachmentGr.getValue('content_type') + ";base64," + ga.getContentBase64(attachmentGr)
    }
}

The same HTML <img> tag will work as we are now supplying the full image as a base64 string which the browser can render. This also means that we can display the image without needing to login.

Version history
Last update:
‎01-17-2019 09:05 AM
Updated by: