Recipes by Category

App Distribution (2) Bundle logic, interface and services for distribution. App Logic (37) The Apex programming language, workflow and formulas for logic. Collaboration (6) The Salesforce Chatter collaboration platform. Database (29) Data persistence, reporting and analytics. Integration (33) Web Service APIs and toolkits for integration. Security (9) Platform, application and data security. Tools (4) Force.com tooling User Interface (36) Visualforce MVC and metadata-drive user interfaces. Web Sites (12) Public web sites and apps with optional user registration and login.
Beta Feedback
Cookbook Home » Uploading a Document using Visualforce and a Custom Controller

Uploading a Document using Visualforce and a Custom Controller

Post by Jeff Douglas  (2010-08-23)

Status: Unverified
Level: novice

Problem

Sometimes you may want to create a process where uploading a document is mandatory. You can create a single Visualforce page with all of the fields for the record plus the field required to upload a document. You could also develop a wizard interface that allows the user to walk through a series of steps in which one would be to upload a document.

Solution

Create a Visualforce page that references a controller (documented below). Note the enctype attribute on the <apex:form> tag. This Visualforce page uses only the fields necessary for uploading a document but can be expanded to include field for other records or documents in the process.

<apex:page controller="FileUploadController">
  <apex:sectionHeader title="Visualforce Example" subtitle="File Upload Example"/>
 
  <apex:form enctype="multipart/form-data">
    <apex:pageMessages />
    <apex:pageBlock title="Upload a File">
 
      <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="{!document.name}" id="fileName"/>
        </apex:pageBlockSectionItem>
 
        <apex:pageBlockSectionItem >
          <apex:outputLabel value="File" for="file"/>
          <apex:inputFile value="{!document.body}" filename="{!document.name}" id="file"/>
        </apex:pageBlockSectionItem>
 
        <apex:pageBlockSectionItem >
          <apex:outputLabel value="Description" for="description"/>
          <apex:inputTextarea value="{!document.description}" id="description"/>
        </apex:pageBlockSectionItem>
 
        <apex:pageBlockSectionItem >
          <apex:outputLabel value="Keywords" for="keywords"/>
          <apex:inputText value="{!document.keywords}" id="keywords"/>
        </apex:pageBlockSectionItem>
 
      </apex:pageBlockSection>
 
    </apex:pageBlock>
  </apex:form>
</apex:page>
Create an Apex class that behaves as the controller in the Visualforce page. The upload() method is key.
public with sharing class FileUploadController {
 
  public Document document {
    get {
      if (document == null)
        document = new Document();
      return document;
    }
    set;
  }
 
  public PageReference upload() {
 
    document.AuthorId = UserInfo.getUserId();
    document.FolderId = UserInfo.getUserId(); // put it in running user's folder
 
    try {
      insert document;
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading file'));
      return null;
    } finally {
      document.body = null; // clears the viewstate
      document = new Document();
    }
 
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'File uploaded successfully'));
    return null;
  }
 
}

Discussion

Visualforce takes care of all the hard work by updating the document from the file that's uploaded. All your controller class needs to do is store it. If you would like to attach the document to a specific record you will need to use the Attachment object instead of the Document object.

Notes

Make sure you take a look at the finally block in the controller code above. The finally block always executes when the try block exits regardless if an error occurs or not. You need to ensure you clear out document’s body (document.body = null) so that the blob is not automatically included in the serialized image of the controller. If you do not clear out the body, you’ll get the following view state error: "Maximum view state size limit (128K) exceeded. Actual viewstate size for this page was…"

Share

Recipe Activity - Please Log in to write a comment

Hi Jeff

I would like an indicator that will let me know if there is an attachment linked to an activity, any help will be appreciated.

by a093000000Xy1mo  (2013-12-18)

Hi there,

I did set the document.body to null but still having the that Maximum view state error when uploading more than the limit ViewState size.. Can you help me, please?

by a093000000XZZfv  (2013-09-05)

Hi,

This s my scenario.
1.User click on “Upload Photo” button to attach any image with current record. It will open standard attachment page(vf page).
2.Type the path of the file or click the "Browse" button to find the file
3.Click the "Attach File" to attach that file.
4.Repeat steps 2 and 3 to attach multiple files.
5.When the upload is completed the file information will appear below.
6.Click the Done button to return to the detail view page.

I created a visualforce page but in controller part  I'm struggling.
Please tell what are steps i have to follow.

by vpm  (2013-07-13)

HI, 

  I would like to add this code to a specific custom object I created. How can I add this field or visual page to that object. Thanks 

by Peter Callister  (2012-08-15)

yesss..it worked !!thanks a lot!!

voted as verified by swati srivastava  (2012-06-22)

It's working but in Document Folders the image was not displayed.why?

voted as verified by sripal reddy  (2012-04-08)

Hi Jeff,

I want to create force.com sites, which will upload documents/attachements along with some additional details of the document.

This above application works fine if I am loggin in salesforce environment. But fields on the forms not editable when we are using this application as site.

Is it possible to use such application as a site? . Any help will be appriciated.

Regards,
Meenakshi

by Meenakshi Musale  (2012-03-29)

Hi Jeff, do you know if it is posible to display the page to upload documents/attachments trhough Force.com Sites.

Thanks

Santi

by Santiago Vargas  (2012-03-08)

great work

voted as verified by samreet matharu  (2012-02-08)

good one

voted as verified by nai j  (2012-02-06)

Great recipe. Is there a way to mass upload documents?

by CESabarre  (2011-08-10)

Yes it works !

voted as verified by a093000000BwsmP  (2011-06-30)

Jeff,
        I think u did it in winter11 apex.what is the maximum  body size did u uploded,and u got any problem colleting the document from desktop (i.e view state).
Thanks
Gopi

by gopi.bangalore02112010  (2010-10-07)

X

Vote to Verify a Recipe

Verifying a recipe is a way to give feedback to others and broaden your own understanding of the capabilities on Force.com. When you verify a recipe, please make sure the code runs, and the functionality solves the articulated problem as expected.

Please make sure:
  • All the necessary pieces are mentioned
  • You have tested the recipe in practice
  • Have sent any suggestions for improvements to the author

Please Log in to verify a recipe

You have voted to verify this recipe.