Activity Forums Salesforce® Discussions how to upload files using Apex code in Salesforce?

  • Achintya

    Member
    September 4, 2019 at 10:12 am

    The easiest way to do this is by using inputFile and assign it to the ContentVersion instance. Like this:

    <apex:page controller="ContentController">
    <apex:form>
        <apex:inputFile value="{!file}" />
        <apex:commandbutton action="{!upload}" value="Upload" />
    </apex:form>
    </apex:page>

    Class:

    public class ContentController {
        public blob file { get; set; }
    
        public PageReference upload() {
            ContentVersion v = new ContentVersion();
            v.versionData = file;
            v.title = 'testing upload';
            v.pathOnClient ='/somepath.txt';
            insert v;
            return new PageReference('/' + v.id);
        }
    }

    If you want to share the ContentVersion file then after inserting DML query the ContentDocumentId from inserted ContentVersion and use ContentDocumentLink to create an association between Record and ContentVersion uploaded a file.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos