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.


Page:



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

Class:



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);
           pr.setRedirect(true);
           return pr;
        }
        return null;
    }    
}


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

Thanks,
Srinivas,
Technology Evangelist,
Trekbin Technologies,
www.trekbin.com

16 comments:

  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:

    ReplyDelete
  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
    -Srinivas.
    }

    ReplyDelete
  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?
    -Erik

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

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

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

    Imran

    ReplyDelete
  7. Srinivas,

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

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

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

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

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

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


    ASC Coding

    ReplyDelete
  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

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

    Thanks

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

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

    ReplyDelete