Customize File Downloads - Salesforce
Hi Salesforce Ohana,
In this article, we will discuss on how to customize file downloads in Salesforce.
What are we going to cover?
- Scenario
- Blocks in the Standard/ declarative approach
- How to Customize File Downloads using Apex
- Customize File Downloads - Flow Execution
- Coding Time
- File Download Restriction Error Handling Flow
- Testing Time
- Limitations
Scenario :
Imagine a scenario where you/ any user(s) uploaded a file in Salesforce and restrict the downloading of the files because of various reasons like security, device factors (Block file download in mobile for Community Users), block downloads when the file already got downloaded more than 3 times, Apply IRM etc.
Blocks in the Standard/ declarative approach :
There is a place in Salesforce where you can control how various file types are handled during upload and download to provide more security but it is organization-level based on file types and it has many limitations.
Where to find? Quick Find > File Upload and Download Security.
How to Customize File Downloads using Apex :
You can use Apex to customize the behavior of files when users attempt to download them inside Salesforce or in the Experience Cloud portal.
ContentDownloadHandlerFactory provides an interface for customizing file downloads. The ContentDownloadHandler class defines values related to whether the download is allowed, and what to do otherwise i.e., redirect to the access denied page.
Customize File Downloads - Flow Execution :
- 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.
- If no implementation is found, the download proceeds. Otherwise, the user is redirected to what has been defined in the ContentDownloadHandler's redirectUrl property.
- If several implementations of Sfc.ContentDownloadHandlerFactory are found, they are cascade handled (ordered by name) and the first one for which the download isn’t allowed is considered.
You can use this methodology in the following use cases
- Prevent a file from downloading based on the user profile, device being used, or file type and size.
- Apply IRM ((Information Resources Management) control to track information, such as the number of times a file has been downloaded.
- Flag suspicious files before downloading, and redirect them for antivirus scanning.
Coding Time :
The below sample code demonstrates how to block file(s) download access in the following scenarios,
- Restrict Customer Service Reps (Profile) from downloading Any Files.
- Restrict Sales Reps (Role) from downloading PDF Files.
- Restrict file downloads in Mobile.
- Restrict file downloads if that file is already downloaded more than 3 times.
Sample Code
Note: The following code might not followed best practices as this is a sample code to demonstrate the use case :)
public class ContentDownloadHandlerFactoryImpl implements Sfc.ContentDownloadHandlerFactory {
public Sfc.ContentDownloadHandler getContentDownloadHandler(List<ID> ids, Sfc.ContentDownloadContext context) {
Sfc.ContentDownloadHandler contentDownloadHandler = new Sfc.ContentDownloadHandler();
//Restrict Customer Service Reps accessing Any Files
Profile userProfile = [SELECT Id,Name FROM Profile WHERE ID =: UserInfo.getProfileId()];
if(userProfile.Name == 'CustomerService Representatives') {
contentDownloadHandler.isDownloadAllowed = false;
//contentDownloadHandler.downloadErrorMessage = 'Downloading a file from a mobile device isn\'t allowed.'; (Optional)
contentDownloadHandler.redirectUrl = '/flow/File_Access_Error_Flow'; // Used Screen Flow to display the error message
return contentDownloadHandler;
}
//Restrict Download access in Mobiles
if(context == Sfc.ContentDownloadContext.MOBILE) {
contentDownloadHandler.isDownloadAllowed = false;
//contentDownloadHandler.downloadErrorMessage = 'Downloading a file from a mobile device is not allowed.'; (Optional)
contentDownloadHandler.redirectUrl = '/flow/File_Access_Error_Flow'; // Used Screen Flow to display the error message
return contentDownloadHandler;
}
//Restrict Sales Reps accessing PDF Files
List<ContentDocument> files = [SELECT Id, Title, FileType, FileExtension FROM ContentDocument WHERE ID IN ( SELECT ContentDocumentId FROM ContentVersion WHERE Id IN :ids)];
UserRole userRole = [SELECT Id,Name FROM UserRole WHERE ID =: UserInfo.getUserRoleId()];
for(ContentDocument file : files){
if(userRole.Name == 'Sales Representatives' && file.FileType == 'PDF') {
contentDownloadHandler.isDownloadAllowed = false;
//contentDownloadHandler.downloadErrorMessage = 'Downloading a file from a mobile device is not allowed.'; (Optional)
contentDownloadHandler.redirectUrl = '/flow/File_Access_Error_Flow'; // Used Screen Flow to display the error message
return contentDownloadHandler;
}
}
//Restrict Download access if the file is already downloaded more than 3 times
List<AggregateResult> fileDownloadCount = [SELECT count(id) DownloadCountByUser, CreatedById FROM ContentVersionHistory WHERE Field = 'contentVersionDownloaded' and ContentVersionId IN : ids GROUP BY CreatedById];
for(AggregateResult count : fileDownloadCount){
Integer userDownloadCount = (Integer)count.get('DownloadCountByUser');
if( userDownloadCount > 3){
contentDownloadHandler.isDownloadAllowed = false;
//contentDownloadHandler.downloadErrorMessage = 'Downloading a file more than 3 times is not allowed.'; (Optional)
contentDownloadHandler.redirectUrl = '/flow/File_Access_Error_Flow'; // Used Screen Flow to display the error message
return contentDownloadHandler;
}
}
contentDownloadHandler.isDownloadAllowed = true;
return contentDownloadHandler;
}
}
File Download Restriction Error Handling Flow :
If you have noticed in the above code, there is a parameter called redirectUrl to redirect the user to the file download restriction error page based on conditions set in the apex.
I have used ScreenFlow to redirect the user to the error page.
Flow Snapshots
Screen Element with Display Text component in it.
That's it. You can save and activate the flow.
Testing Time :
Let's take one example for our testing as the file will not be downloaded again of it is already downloaded more than 3 times.
I have uploaded the sample image into the Salesforce File and I have already downloaded it more than 3 times. Now if I attempt to download, I will get an error message.
Error Screen
Limitations :
- If a SOAP API operation triggers a download, it goes through the Apex class that checks whether the download is allowed. If a download isn’t allowed, a redirection can’t be handled, and an exception containing an error message is returned instead.
- If you use the below REST API Endpoint, then the apex class that implements Sfc.ContentDownloadHandlerFactory won’t be invoked.
- /services/data/v59.0/sobjects/ContentVersion/contentversionid
Resources :
- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_salesforce_files_customize_downloads.htm
- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_salesforce_files_customize_downloads_examples.htm
- https://help.salesforce.com/s/articleView?id=sf.admin_files_type_security.htm&type=5
- https://help.salesforce.com/s/articleView?id=000385125&type=1
Hope you have learnt something new today.
Happy Trailblazing................!!!!

Comments
Post a Comment