+ Start a Discussion
vineetha pattuvineetha pattu 

how to upload multiple attachments from apex? please provide me some sample code

Best Answer chosen by vineetha pattu
SandhyaSandhya (Salesforce Developers) 
Hi Vineetha,

Below is the sample code you can change according to your requirements.

Controller
--------------
 
public class MultipleUploadController  
    {     
        //Picklist of tnteger values to hold file count  
        public List<SelectOption> filesCountList {get; set;}  
        //Selected count  
        public String FileCount {get; set;}  
          
        public List<Attachment> allFileList {get; set;}  
          
        public MultipleUploadController(ApexPages.StandardController controller)  
        {  
            //Initialize    
            filesCountList = new List<SelectOption>() ;  
            FileCount = '' ;  
            allFileList = new List<Attachment>() ;  
              
            //Adding values count list - you can change this according to your need  
            for(Integer i = 1 ; i < 11 ; i++)  
                filesCountList.add(new SelectOption(''+i , ''+i)) ;  
        }  
          
        public Pagereference SaveAttachments()  
        {  
            String accId = System.currentPagereference().getParameters().get('Id');  
            if(accId == null || accId == '')  
                ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'No record is associated. Please pass record Id in parameter.'));  
            if(FileCount == null || FileCount == '')  
                ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'Please select how many files you want to upload.'));  
      
            List<Attachment> listToInsert = new List<Attachment>() ;  
              
            //Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);  
            for(Attachment a: allFileList)  
            {  
                if(a.name != '' && a.name != '' && a.body != null)  
                    listToInsert.add(new Attachment(parentId = 'a0728000003FqcD', name = a.name, body = a.body)) ;  
            }  
              
            //Inserting attachments  
            if(listToInsert.size() > 0)  
            {  
                insert listToInsert ;  
                ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.INFO, listToInsert.size() + ' file(s) are uploaded successfully'));  
                FileCount = '' ;  
            }  
            else  
                ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'Please select at-least one file'));  
                  
            return null;  
        }  
          
        public PageReference ChangeCount()  
        {  
            allFileList.clear() ;  
            //Adding multiple attachments instance  
            for(Integer i = 1 ; i <= Integer.valueOf(FileCount) ; i++)  
                allFileList.add(new Attachment()) ;  
            return null ;  
        }  
    }

Visualforce
----------------
<apex:page standardController="Bottle__c" extensions="MultipleUploadController">  
        <apex:form >  
            <apex:pageBlock title="Upload Multiple Attachment to Object">      
                <apex:pageBlockButtons >  
                    <apex:commandButton value="Upload"  action="{!SaveAttachments}"/>  
                </apex:pageBlockButtons>         
                <apex:pageMessages id="MSG"/>  
                <apex:actionFunction name="ChangeCount" action="{!ChangeCount}"/>  
                  
                <apex:pageblocksection >                      
                    <apex:pageBlockSectionItem >  
                        <apex:outputLabel value="How many files you want to upload?"/>  
                        <apex:selectList onchange="ChangeCount() ;" multiselect="false" size="1" value="{!FileCount}">  
                            <apex:selectOption itemLabel="--None--" itemValue=""/>  
                            <apex:selectOptions value="{!filesCountList}"/>  
                        </apex:selectList>  
                    </apex:pageBlockSectionItem>  
                </apex:pageblocksection>  
                <apex:pageBlockSection title="Select Files" rendered="{!IF(FileCount != null && FileCount != '', true , false)}">  
                    <apex:repeat value="{!allFileList}" var="AFL">  
                        <apex:inputfile value="{!AFL.body}" filename="{!AFL.Name}" />        
                    </apex:repeat>  
                </apex:pageBlockSection>  
                  
            </apex:pageBlock>  
        </apex:form>  
    </apex:page>



Please accept my solution as Best Answer if my reply was helpful. It will make it available for other as the proper solution. If you felt I went above and beyond, you can give me kudos.
 
Thanks and Regards
Sandhya

 

All Answers

SandhyaSandhya (Salesforce Developers) 
Hi Vineetha,

Below is the sample code you can change according to your requirements.

Controller
--------------
 
public class MultipleUploadController  
    {     
        //Picklist of tnteger values to hold file count  
        public List<SelectOption> filesCountList {get; set;}  
        //Selected count  
        public String FileCount {get; set;}  
          
        public List<Attachment> allFileList {get; set;}  
          
        public MultipleUploadController(ApexPages.StandardController controller)  
        {  
            //Initialize    
            filesCountList = new List<SelectOption>() ;  
            FileCount = '' ;  
            allFileList = new List<Attachment>() ;  
              
            //Adding values count list - you can change this according to your need  
            for(Integer i = 1 ; i < 11 ; i++)  
                filesCountList.add(new SelectOption(''+i , ''+i)) ;  
        }  
          
        public Pagereference SaveAttachments()  
        {  
            String accId = System.currentPagereference().getParameters().get('Id');  
            if(accId == null || accId == '')  
                ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'No record is associated. Please pass record Id in parameter.'));  
            if(FileCount == null || FileCount == '')  
                ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'Please select how many files you want to upload.'));  
      
            List<Attachment> listToInsert = new List<Attachment>() ;  
              
            //Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);  
            for(Attachment a: allFileList)  
            {  
                if(a.name != '' && a.name != '' && a.body != null)  
                    listToInsert.add(new Attachment(parentId = 'a0728000003FqcD', name = a.name, body = a.body)) ;  
            }  
              
            //Inserting attachments  
            if(listToInsert.size() > 0)  
            {  
                insert listToInsert ;  
                ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.INFO, listToInsert.size() + ' file(s) are uploaded successfully'));  
                FileCount = '' ;  
            }  
            else  
                ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'Please select at-least one file'));  
                  
            return null;  
        }  
          
        public PageReference ChangeCount()  
        {  
            allFileList.clear() ;  
            //Adding multiple attachments instance  
            for(Integer i = 1 ; i <= Integer.valueOf(FileCount) ; i++)  
                allFileList.add(new Attachment()) ;  
            return null ;  
        }  
    }

Visualforce
----------------
<apex:page standardController="Bottle__c" extensions="MultipleUploadController">  
        <apex:form >  
            <apex:pageBlock title="Upload Multiple Attachment to Object">      
                <apex:pageBlockButtons >  
                    <apex:commandButton value="Upload"  action="{!SaveAttachments}"/>  
                </apex:pageBlockButtons>         
                <apex:pageMessages id="MSG"/>  
                <apex:actionFunction name="ChangeCount" action="{!ChangeCount}"/>  
                  
                <apex:pageblocksection >                      
                    <apex:pageBlockSectionItem >  
                        <apex:outputLabel value="How many files you want to upload?"/>  
                        <apex:selectList onchange="ChangeCount() ;" multiselect="false" size="1" value="{!FileCount}">  
                            <apex:selectOption itemLabel="--None--" itemValue=""/>  
                            <apex:selectOptions value="{!filesCountList}"/>  
                        </apex:selectList>  
                    </apex:pageBlockSectionItem>  
                </apex:pageblocksection>  
                <apex:pageBlockSection title="Select Files" rendered="{!IF(FileCount != null && FileCount != '', true , false)}">  
                    <apex:repeat value="{!allFileList}" var="AFL">  
                        <apex:inputfile value="{!AFL.body}" filename="{!AFL.Name}" />        
                    </apex:repeat>  
                </apex:pageBlockSection>  
                  
            </apex:pageBlock>  
        </apex:form>  
    </apex:page>



Please accept my solution as Best Answer if my reply was helpful. It will make it available for other as the proper solution. If you felt I went above and beyond, you can give me kudos.
 
Thanks and Regards
Sandhya

 
This was selected as the best answer
sandeep reddy 37sandeep reddy 37
which type of attchment you want emailattachment file or  just attachment ok i understand how to handle allachment class so see below code

public void saveAttachment(){
String encodedContentsString = System.currentPageReference().getParameters().get('fileContents');
Id accountId = System.currentPageReference().getParameters().get('accountId');
Attachment attachment = new Attachment();
attachment.Body = Blob.valueOf(encodedContentsString);
attachment.Name = String.valueOf('test.txt');
attachment.ParentId = accountId; insert attachment;
}  
 i hope helpful for u?
vineetha pattuvineetha pattu
Thank you sandhya and sandeep .