Showing posts with label Content Version. Show all posts
Showing posts with label Content Version. Show all posts

Wednesday, February 12, 2020

How to get related files of the record using apex in salesforce

Use the below sample code to get the files related to the record using apex.
This code works for bulk records pass the list of parent ids to the method, based on parent ids it returns the files associated with the parent record.

Apex Code
public inherited sharing class ContentUtility {
 public static map<Id, list<ContentVersion>> getRelatedFiles(list<Id> lstParentIds) {

        map<Id, list<ContentVersion>> mapParentIdAndFiles = new map<Id, list<ContentVersion>>();
        map<Id, Id> mapCntIdParentId = new map<Id, Id>();

        for(ContentDocumentLink cntLink : [Select Id, ContentDocumentId, LinkedEntityId From ContentDocumentLink Where LinkedEntityId IN :lstParentIds]) {
            mapCntIdParentId.put(cntLink.ContentDocumentId, cntLink.LinkedEntityId);
        }

        if(!mapCntIdParentId.isEmpty()) {
            for(ContentVersion cv :  [SELECT Id, Title, VersionData, ContentDocumentId FROM ContentVersion WHERE ContentDocumentId IN :mapCntIdParentId.keySet() AND IsLatest = True]) {
               
                if(!mapParentIdAndFiles.containsKey(mapCntIdParentId.get(cv.ContentDocumentId))) {
                    mapParentIdAndFiles.put(mapCntIdParentId.get(cv.ContentDocumentId), new list<ContentVersion>());
                }
                
                mapParentIdAndFiles.get(mapCntIdParentId.get(cv.ContentDocumentId)).add(cv);
            }
        }
        
        return mapParentIdAndFiles;
    } 
}

Sample Code
System.debug('Related Files ===>'+ContentUtility.getRelatedFiles(new list<Id>{'a1Z54000001NplZ'}));

Thursday, February 6, 2020

How to download the files using URL from salesforce

Note: To download the file, require the Content Version record Ids

For Single File

Use the below URL to download the single file from the salesforce.
URL https://<YOUR_SFDC_BASE_URL>/sfc/servlet.shepherd/version/download/068XXXXXXXXXXXX

String idCntDoc = '068XXXXXXXXXXXX';
String strURL = URL.getSalesforceBaseUrl().toExternalForm() + '/sfc/servlet.shepherd/version/download/' + idCntDoc;
System.debug('URL ===> '+strURL);

For Multiple Files

URL: https://<YOUR_SFDC_BASE_URL>/sfc/servlet.shepherd/version/download/068XXXXXXXXXXXX/068XXXXXXXXXXXX
above URL downloads the files in ZIP folder

list<String> lstCntVersionIds = new list<String>{'068XXXXXXXXXXXX', '068XXXXXXXXXXXX'};

String strURL = URL.getSalesforceBaseUrl().toExternalForm() + '/sfc/servlet.shepherd/version/download/';

for(String iterator : lstCntVersionIds) {
    strURL += iterator + '/';
}

strURL = strURL.removeEnd('/');

System.debug('URL ===> '+strURL);