Uploading a document in apex salesforce using custom controller

U

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. code  below is an example

//VISUALFORCE PAGE
<apex:page controller=”docex”>
<apex:outputLabel value=”Document Name”/>
<apex:inputText id=”name” value=”{!d.name}”/>

<apex:outputLabel value=”Upload Document”/>
<apex:inputFile value=”{!file}” />
<apex:commandButton value=”Save” action=”{!insert}” id=”save”/>
</apex:page>

//APEX CLASS
public class docex
{
Document d{get;set;}
public ID folderid{get;set;}

public docex
{
d= new Document();
}
public void insert()
{
//document
folderid=UserInfo.getUserId();    //uses the current user id as folder id
d.body=file;            // body field in document object which holds the file.
d.folderid=folderid;        //folderid where the document will be stored
insert d;
}

}

for further reference you can store the id of an document along with other fields in your custom object . and retrieve the contents of the document object by using soql query:

document d=[select body, id , name from document where id=”<stored 18 character id>”]

About the author

ankit.shah
By ankit.shah

Category