accessing static resource in apex
You can simply query them.
StaticResource sr = [SELECT Id, Body FROM StaticResource WHERE Name = 'MyJsonFile' LIMIT 1];
String body = sr.Body.toString();
Access Static Resource
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:
- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_System_PageReference_getContent.htm
You can also use the PageReference.forResource()
method, then add the path/filename onto it.
String myUrl = PageReference.forResource('MyStaticResource').getUrl();
myUrl = myUrl.subString(0, myUrl.indexOf('?'));
system.debug(myUrl + '/path/myImage.png');
PageReference.forResource('MyStaticResource').getUrl()
return a string with the base URL and a number of parameters you don't need, which is why I've used the subString method.