accessing static resource in apex

I know that we can access static resources in visualforce page as follows;

  {!URLFOR($Resource.UploadTemplate)}

How can we access the static resource in APEX class? And if it is in a zip file, how can I specify the specific file from within the zip as it is allowed in visualforce ?

Thanks in advance

Answer

If you want to get some file from zipped static resource, you can use getContent():

StaticResource static_resource = [SELECT Id, SystemModStamp
                                  FROM StaticResource 
                                  WHERE Name = 'My Zip Array'
                                  LIMIT 1];
String url_file_ref = '/resource/'
                    + String.valueOf(((DateTime)static_resource.get('SystemModStamp')).getTime())
                    + '/' 
                    + static_resource.get('Name')
                    + '/myfile.json';
PageReference file_ref = new PageReference(url_file_ref);
String res_json_body = file_ref.getContent().toString();

Please, remember, you can not always use this due to limitation on getContent() (it can not be used in triggers) and latest salesforce updates.

References:

Attribution
Source : Link , Question Author : vanessen , Answer Author : kurunve

Leave a Comment