Uploading an Attachment using Visualforce and a Custom Controller

This is a follow up post to Uploading a Document using Visualforce and a Custom Controller showing an example for uploading an attachment for a Contact. The Visualforce page and Controller is very similar with a few exceptions.


Attachments are different than documents and are only available for the following objects:

  • Account
  • Asset
  • Campaign
  • Case
  • Contact
  • Contract
  • Custom objects
  • EmailMessage
  • EmailTemplate
  • Event
  • Lead
  • Opportunity
  • Product2
  • Solution
  • Task

Salesforce.com restricts an attachment size to a maximum size of 5 MB. For a file attached to a Solution, the limit is 1.5MB. The maximum email attachment size is 3 MB. You can contact Salesforce.com support and possibly have them increase these limits. They should be able to increase the document and attachment size to 25MB. They cannot increase the limits for emails.

AttachmentUploadExample

<apex:page controller="AttachmentUploadController">
 <apex:sectionHeader title="Visualforce Example" subtitle="Attachment Upload Example"/>
 
 <apex:form enctype="multipart/form-data">
  <apex:pageMessages />
  <apex:pageBlock title="Upload a Attachment">
 
 <apex:pageBlockButtons >
  <apex:commandButton action="{!upload}" value="Save"/>
 </apex:pageBlockButtons>
 
 <apex:pageBlockSection showHeader="false" columns="2" id="block1">
 
  <apex:pageBlockSectionItem >
   <apex:outputLabel value="File Name" for="fileName"/>
   <apex:inputText value="{!attachment.name}" id="fileName"/>
  </apex:pageBlockSectionItem>
 
  <apex:pageBlockSectionItem >
   <apex:outputLabel value="File" for="file"/>
   <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file"/>
  </apex:pageBlockSectionItem>
 
  <apex:pageBlockSectionItem >
   <apex:outputLabel value="Description" for="description"/>
   <apex:inputTextarea value="{!attachment.description}" id="description"/>
  </apex:pageBlockSectionItem>
 
 </apex:pageBlockSection>
 
  </apex:pageBlock>
 </apex:form>
</apex:page>

AttachmentUploadController

public with sharing class AttachmentUploadController {
 
 public Attachment attachment {
 get {
 if (attachment == null)
  attachment = new Attachment();
 return attachment;
  }
 set;
 }
 
 public PageReference upload() {
  
  attachment.OwnerId = UserInfo.getUserId();
  attachment.ParentId = '0037000000lFxcw'; // the record the file is attached to
  attachment.IsPrivate = true;
  
  try {
 insert attachment;
  } catch (DMLException e) {
 ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
 return null;
  } finally {
 attachment = new Attachment(); 
  }
  
  ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
  return null;
 }

}