April 23, 2021

How to call apex class when a file is downloaded in Salesforce?

Use Sfc.ContentDownloadHandlerFactory interface to call apex class when a file is downloaded in Salesforce.
 
Sample Code:
public class ContentDownloadHandlerFactoryImpl implements Sfc.ContentDownloadHandlerFactory {

    public Sfc.ContentDownloadHandler getContentDownloadHandler( List<ID> listIds, Sfc.ContentDownloadContext context ) {
    
        Sfc.ContentDownloadHandler contentDownloadHandler = new Sfc.ContentDownloadHandler();
        
        /* To Prevent downloading it from Mobile */
        if ( context == Sfc.ContentDownloadContext.MOBILE ) {
        
            contentDownloadHandler.isDownloadAllowed = false;
            contentDownloadHandler.downloadErrorMessage = 'Downloading a file from a mobile device is not allowed.';
            return contentDownloadHandler;
        
        }
    
        contentDownloadHandler.isDownloadAllowed = true;
        return contentDownloadHandler;
    
    }

}
 
Note:
When a download is triggered either from the UI, Connect API, or an sObject call retrieving ContentVersion.VersionData, implementations of the Sfc.ContentDownloadHandlerFactory are looked up.
 
System.debug( 'Value is ' + [ SELECT Id, VersionData FROM ContentVersion WHERE Id = '0684x00000377ZUAAY' ] ); 
If the above code is executed, then also the apex class will be called.
 
But, if we use the below REST API Endpoint, then the apex class won't be invoked.
/services/data/v51.0/sobjects/ContentVersion/0684x00000377ZUAAY
 

No comments:

Post a Comment