Search In This Blog

2020-07-03

Upload file/attachment | Apex Visualforce | Salesforce

template:
<apex:form>
    <apex:inputFile value="{!file}" />
<apex:commandbutton action="{!upload}" value="Upload" />
</apex:form>
Apex:
// file
public blob file {get;set;}
pubilc PageReference upload(){
    ContentVersion photofile = new ContentVersion();
    if(file != null){
        photofile.VersionData = file;
        photofile.Title='title';
        photofile.IsMajorVersion = false;
        photofile.PathOnClient='/title';
        insert photofile;
    }
    try{
        insert photofile;
    } catch(Exception Ex){
        System.debug('Ex==>'+Ex);
    }
    photofile = [select id, ContentDocumentId from ContentVersion WHERE Id =: photofile.Id];

    ContentDocumentLink cdl = new ContentDocumentLink();
    cdl.ContentDocumentId = photofile.ContentDocumentId;
    cdl.LinkedEntityId = [parentId]; 
    cdl.ShareType = 'V';
    cdl.Visibility = 'AllUsers';

    try{
        insert cdl;
    } catch(Exception Ex){
        System.debug('Ex==>'+Ex); 
    }
}
// Attachment
public blob file {get;set;}
pubilc PageReference upload(){
    try {
        if(file != null){
            attachment.body = file;
            attachment.name='title';
            attachment.OwnerId = UserInfo.getUserId();
            attachment.ParentId = [parentId];
            attachment.IsPrivate = true;

            insert attachment;
        }else{
            attachment = new Attachment();
        }
    } catch (Exception e) {
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'error'));
        return null;
    }
}