Upload a file as an attachment to a record using Visualforce Page

Scenario - Provide the file upload Page to the users. Once user uploads the file, attach it to the Account Record.

Step 1: Create an Apex class named “attachmentsample”

saveDoc method of attachmentSample class getting the recordId from Page Reference and using it to attach the file. 

				
					public class attachmentSample {
    public attachmentSample(ApexPages.StandardController controller) {

    }
    Public Attachment myfile;
    Public Attachment getmyfile()
    {
        myfile = new Attachment();
        return myfile;
    }
   
    Public Pagereference saveDoc()
    {
        String accid = System.currentPagereference().getParameters().get('id');
        Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);
         
        //insert the attachment
        insert a;
        return NULL;
    }   

}
				
			

Step 2: Create a Visualforce page named “attachment”

				
					<apex:page standardController="Account" extensions="attachmentsample">

<apex:form >
  <apex:sectionHeader title="Upload a Attachment into Salesforce"/>
  <apex:pageblock >
      <apex:pageblocksection columns="1">
          <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
          <apex:commandbutton value="Save" action="{!Savedoc}"/>
      </apex:pageblocksection>
  </apex:pageblock>   
</apex:form> 

</apex:page>
				
			

Step 3: Custom Button

Create a custom button (Detail Page button) on Account and select the new Visualforce page that you created earlier

Step 4: Update Account Layout

Add the new button to the Account Page layout.

Step 5: Quick Test:

If you do not wish to do Step3 and Step4 then follow this.

Paste the following URL in your browser
http://yoursalesforceinstance.com/apex/attachment?id={accountId}

References