Upload a file as an Attachment to a record using Visualforce

11:10 PM

This example illustrates the way to upload a file and attach it against any record using Visualforce. The file that you upload using this will be available in the "Notes & Attachments" related list for the record.

Click here if you are looking to upload a file into "Documents".

Step 1: Create an Apex class named "attachmentsample" . Paste the code below.


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" and paste the code below.


<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>

Quick Test:
If you do not wish to do Step3 and 4 do this. Paste the following URL in your browser
http://yoursalesforceinstance.com/apex/attachment?id=0017000000eiDgy

ID should be a Valid Account Id of your instance.

Step 3:
Create a custom button (Detail Page button) on Account and select the new Visualforce page that you created as the source.

Step4:
Add the button created in Step3 to the Account Page layout.

You can test this by navigating to any account and clicking on the button that you created in Step3.
You may test

21 comments

  1. Awesome... Thanks

    ReplyDelete
  2. nice work, now if only you could upload it to Content and select a public workspace to publish it to.

    ReplyDelete
  3. How do you write the test case for the above controller?

    ReplyDelete
  4. How can i display list of attached documents?

    Regards,
    Devendra S

    ReplyDelete
  5. error while uploading:
    System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Parent]: [Parent]

    ReplyDelete
  6. Nice one :) its working fine, have any idea how to download the attachments using Bulk API ?

    ReplyDelete
  7. What if I want to just add an attachemnt to an VF page I created?

    ReplyDelete
  8. Clarification, I want to add attachments to the VF page yet when saved, available as related lists within SF

    ReplyDelete
  9. This is a fantastic work around for the permission limitations of portal users not being able to attach documents to records.

    ReplyDelete
  10. Doesn't work, I get this error:

    System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Parent]: [Parent]
    Error is in expression '{!Savedoc}' in component in page attachment

    Class.attachmentsample.Savedoc: line 20, column 1

    ReplyDelete
    Replies
    1. Actually it does work. I get the same error message when I tried to run it without adding Account's page layout as a custom button. After I created to custom button tied with visualforce page and added custom button to Account's page layout, it worked for me.

      Delete
  11. Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Parent]: [Parent]
    Error is in expression '{!Savedoc}' in component in page attachment: Class.attachmentsample.Savedoc: line 21, column 1

    I got above error

    ReplyDelete
  12. Whoever got this error REQUIRED_FIELD_MISSING, Required fields are missing: [Parent]: [Parent]
    insert ?id= after yout URL .

    ReplyDelete
  13. Hi i want to upload the file to my custom vfpage and attach it to the record while the submitting the record. Can you let me know this will be done or not.

    ReplyDelete
  14. I am getting an error for file size. It says that I can't attach a file using this process that is more than 135KB.

    ReplyDelete
  15. Hi all,
    I Want to upload a file from visual force page to wordpress app which is hosted on aws.
    getting cors error. Can't post data.

    any help would be appreciate.

    Thanks & Regards,
    Nitin Shukla

    ReplyDelete
  16. How to upload multiple files at a time. please help with this.

    ReplyDelete
  17. same logic is extended to upload multiple files...it fails with View State error

    ReplyDelete
  18. Hi,

    When i try to put with name and body, iam getting Error: Unknown property 'Call_Report__cStandardController.mAttachment' .

    can someone help me

    Thanks Inadvance

    ReplyDelete
  19. Can you post test class for same code

    ReplyDelete
  20. Works great in sandbox! However, what would be the test class for this so I may deploy to production?

    ReplyDelete