Thursday, April 29, 2010

Visualforce File Upload - for Any SObject

How to Upload Attachment to any SObject using Visualforce

This article explains how you can upload file attachments to any SOobject using Visualforce.


<apex:page standardController="YourSObjectName" extensions="VFFileUpload">
      <apex:pageBlock title="Upload Attachment">
            <apex:inputFile style="width:100%" id="fileToUpload" value="{!fileBody}" filename="{!fileName}" />
            <apex:commandButton value="Upload Attachment" action="{!UploadFile}"/>


public class VFFileUpload
    public Id recId
    {    get;set;    }
    public VFFileUpload(ApexPages.StandardController ctlr)
       recId = ctlr.getRecord().Id;     
    public string fileName 
    {    get;set;    }
    public Blob fileBody 
    {    get;set;    }
    public PageReference UploadFile()
        PageReference pr;
        if(fileBody != null && fileName != null)
          Attachment myAttachment  = new Attachment();
          myAttachment.Body = fileBody;
          myAttachment.Name = fileName;
          myAttachment.ParentId = recId;
          insert myAttachment;
           pr = new PageReference('/' + myAttachment.Id);
           return pr;
        return null;

You can use the above code for any object whether it is standard or custom. Happy coding!

Technology Evangelist,
Trekbin Technologies,


  1. Hi ,

    I have this problem :

    Apex script unhandled exception by user/organization: 005A0000000SQvc/00DA0000000YfN2

    Visualforce Page: /apex/UploadAttachment

    caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [ParentId]: [ParentId]

    Class.VFFileUpload.UploadFile: line 15, column 5
    External entry point

    Debug Log:

  2. The page has to be launched from a detail page button of an SObject like Contact or Some Custom Object.
    In your case The Id value is missing, that is why the error.
    You can pass the id in the URL and get it in the constructor also like this,
    public VFFileUpload(ApexPages.StandardController ctlr)
    recId = ApexPages.CurrentPage().getParameters().get('Id');
    'Hope this helps

  3. I think he was trying to attach a file to a new object, which of course doesn't yet have an id. How can you get the id before you actually save the record?

  4. If you want to attach the uploads to a new, not yet extant, object, make the "myAttachment" variable belong to the controller, not just scoped within the upload function. Then the attachment remains as part of the controller until the controller finally runs save().

    Within your controller's save() function you do this:

    insert myNewRecord;
    myAttachment.parentId = myNewRecord.Id
    insert myAttachment;

    So within save(), you're creating the new record of the object type related to the controller. Once you insert it, you have an idea. Now apply that ID to the attachment.

  5. is there any way you can store the file path from where you are attaching this file?
    Say, there is a custom URL field in which I want to store the source file path, can I fd that? I have tried this by all means but not able to achieve...thanks for your help!

  6. Hi Srinivas,

    Just wondering if you have any tips on how I could implement the upload to handle multiple documents in the same upload action.


  7. Srinivas,

    I am trying to take Input File and uploading .csv file.
    Can I have the preview of the file which I imported.

  8. i can't able to get the line you said.....
    (make the "myAttachment" variable belong to the controller, not just scoped within the upload function. Then the attachment remains as part of the controller until the controller finally runs save().)

    could you please explain deep?

  9. How can the user be notified if the attachment size is too big? SF has file size limits of 5 MB.

  10. Hi Srinivas,

    I am having an issue with required field validation on a form along with upload file.But if the validation of form fails then it removes the file path.It confuses end users.How to fix this?

  11. Hi, I got an issue on rendered the page with inputFile... Any suggestion?

  12. Thank you for the info. It sounds pretty user friendly. I guess I’ll pick one up for fun. thank u

    ASC Coding

  13. Hai all,
    I am creating a Visualforce page to upload photos and these photos are saved in the attachments object.How can i Upload Image(above 1MB to 10MB) Attachments to Salesforce using Javascript Remoting

  14. Hi,

    I tried to implement this functionality inside a form which has rerender/ oncomplete buttons and I am getting this error:
    apex:inputFile can not be used in conjunction with an action component, apex:commandButton or apex:commandLink that specifies a rerender or oncomplete attribute.

    Can you pls suggest solution for this?


  15. Getting the following error: Error: Documents line 27, column 30: The entity name must immediately follow the '&' in the entity reference
    Error Error: The entity name must immediately follow the '&' in the entity reference.

    Line 27: if(fileBody != null && fileName != null) Does this need to be the name of my document in which I want to be shown?

  16. add parent id like:
    att.ParentId = '0016F00001wlrGL'; // the record the file is attached to, then u wont get error

  17. want to create a new lead record and attachment in one go.but not getting how to ralated those both things
    vf page:

    public class myWeb2LeadExtension {

    private final Lead weblead;

    public myWeb2LeadExtension(ApexPages.StandardController
    stdController) {
    weblead = (Lead)stdController.getRecord();


    public PageReference saveLead() {
    try {


    catch(System.DMLException e) {
    return null;

    PageReference p = Page.ThankYou;
    return p;

    public class attachmentsample {

    public String Leadid;
    public attachmentsample(ApexPages.StandardController controller) {
    String Leadid = System.currentPagereference().getParameters().get('id');

    Public Attachment myfile;
    Public Attachment getmyfile()
    myfile = new Attachment();
    return myfile;

    Public Pagereference Savedoc()
    // String Leadid = System.currentPagereference().getParameters().get('id');

    Attachment a = new Attachment(parentId = Leadid,, body = myfile.body);

    /* insert the attachment */
    insert a;

    return NULL;

    getting parentid missing exception.
    anyone knows why i'm getting this problem

  18. I am able to create pdf under notes and atachments but its creating multiple attachments. Need Help.

    VF Page: (DecisionLetter)-- Data is on this page

    VF Page: (DecisionLetter_V2)

    public class attachPDFToContact {
    public string recId {set;get;}

    public attachPDFToContact(ApexPages.StandardController standardPageController) {
    recId = standardPageController.getId();

    //method called from the Visualforce's action attribute
    public void attachPDF() {
    Blob pdfBlob;
    try {
    PageReference pdfPage = Page.DecisionLetter_v2;
    pdfBlob = pdfPage.getContent();
    }catch(exception e){
    pdfBlob = blob.valueOf('this is from excetion '+e.getMessage());
    Attachment attach = new Attachment(ParentId = ApexPages.currentPage().getParameters().get('id'), Name = 'DecisionLetter - '+ system.Now() + '.pdf', body = pdfBlob);
    insert attach;