File attachment using Apex

To attach a file to an object via apex involves using Contentversion and ContentDocumentLink object.
ContentVersion object is available in version 20.0 and above.
Please do keep into consideration that the maximum number of versions that can be published over 24 hour period is limited to 200,000


Let's create a file attachment to a contact object. We will be creating a very simple text file with a content
"This is a test data"


Following Code will illustrate to create a text file and attach it to contact object.

Go to Contact object and look for text file under notes and attachment section.

try{
    string textFile = 'This is a test data';
    ContentVersion DocVer = New ContentVersion();
    docVer.ContentLocation = 'S';
    docVer.PathOnClient= 'Demo.txt';
    docver.Title= 'Demo.txt';
    Blob textData = Blob.valueOf(textFile);
    docver.VersionData =textData;
    insert DocVer;
    
    string Versid =[select contentDocumentid from contentVersion where id =: DocVer.id].contentDocumentid;
    ContentDocumentLink Doclink = New ContentDocumentLink();
    doclink.ContentDocumentId = Versid;
    doclink.linkedEntityId =contactid;
    doclink.sharetype = 'I';
    doclink.visibility = 'AllUsers';
    insert doclink;
    
    
    
}
catch(exception ex)
{
    system.debug(ex.getmessage());
    
}

Go to Contact object and look for text file under notes and attachment section.

 

Comments

Popular posts from this blog

The Salesforce Certification Frenzy: Balancing Quantity with Quality in a Changing Market

The Ultimate Guide to Building a Salesforce Career: Roles, Skills, and Strategies for Success