Stat Tracker

Tuesday, January 4, 2011

Visualforce Page - Attachment Upload Example

I see a lot of folks posting questions in the developer forums about uploading an attachment into Salesforce through a Visualforce Page. It is actually very easy to accomplish this.

You will want to use the apex tag <apex:inputFile> to put the FileChooser Popup on the VF Page.

Inside your controller, you simply create an empty Document object, and you bind the <apex:inputFile> tag to the Document in the controller with this code here:

<apex:inputFile value="{!attach.body}" filename="{!attach.name}"/>

With your bindings all set, you just need to create an action on the controller to retrieve the values from the insert the Attachment Object. This can be done in the upload() method in the code below.

This small custom controller and Visualforce page will allow a user to upload a file and create an attachment on the record for an ID give. Here are the screenshots to show this in action.

 Once the upload() method finishes it sends the user to the new Attachment.



Here is the full code below:

AttachmentUploadController - Apex Controller
//Simple Custom Controller to Insert an Attachment into Salesforce
public with sharing class AttachmentUploadController
{
    public String parentId {get;set;}
    public Attachment attach {get;set;}
  
    public AttachmentUploadController()
    {
        attach = new Attachment();
    }
  
    //When user clicks upload button on Visualforce Page, perform upload/insert
    //Redirect user to newly inserted document
    public ApexPages.Pagereference upload()
    {
       
        //This shows how to insert an Attachment
        attach.ParentId = parentId;
        insert attach;
       
        return new ApexPages.Standardcontroller(attach).view();  
    }
}


AttachmentUpload - Visualforce Page
<apex:page controller="AttachmentUploadController">
    <apex:form >
        <apex:outputText value="Parent Object ID: "/><apex:inputText value="{!parentId}"/><br/>
        <apex:outputText value="Input File:  "/><apex:inputFile value="{!attach.body}" filename="{!attach.name}"/><br/>
        <apex:commandButton value="Upload" action="{!upload}"/>
    </apex:form>
</apex:page>



Its really that easy. Of course you'll need to add some error handling to check for null files and stuff like that, but the basics are super easy. This is a good example of a development activity that Apex makes quick and easy.

Of course when you hit Apex limits or things it doesn't do well, thats when you want to pull your hair out.