Showing posts with label Relative URL. Show all posts
Showing posts with label Relative URL. Show all posts

May 15, 2012

Static Resource URL in Apex

Question is how to get the Static Resource's URL in Apex, so below is the function which will return the relative URL (also supports namespace-resources)


public class StaticResourceURL
{
    //Pass the resource name
    public static String GetResourceURL(String resourceName)
    {
        //Fetching the resource
        List resourceList = [SELECT Name, NamespacePrefix, SystemModStamp FROM StaticResource WHERE Name = :resourceName];
                            
        //Checking if the result is returned or not
        if(resourceList.size() == 1)
        {
           //Getting namespace
           String namespace = resourceList[0].NamespacePrefix;
           //Resource URL
           return '/resource/' + resourceList[0].SystemModStamp.getTime() + '/' + (namespace != null && namespace != '' ? namespace + '__' : '') + resourceName; 
        }
        else return '';
    }
}


Use this in debug logs to verify :


System.debug(':::: ' + StaticResourceURL.GetResourceURL('StaticResourceName')) ;


*Please change the "StaticResourceName" with your Static resource name in above line