Home SALESFORCEAPEX Save the Attachment using Apex Class and Visualforce Page in Salesforce

Save the Attachment using Apex Class and Visualforce Page in Salesforce

Attachment field allows users to be able to attach notes and attachments to custom object records. This allows you to attach external documents to any object record, in much the same way that you can add a PDF or photo as an attachment to an email. This option is only available when you are creating a new object. Here I have an example for save an attachment in APEX.

Apex Class:
[JAVA]
public class status {
private final Applicant__c applicant;
public Blob resume {get; set;}
public String contentType {get; set;}
public String fileName {get; set;}

public status(ApexPages.StandardController stdController) {
this.applicant=(Applicant__c)stdController.getRecord();
}
public PageReference saveApplication() {

try {
insert(applicant);
} catch(System.DMLException e) {
ApexPages.addMessages(e);
return null;
}

if(resume!=null){
Attachment attach=new Attachment();
attach.Body=resume;
attach.Name=filename;
attach.ContentType=contentType;
attach.ParentID=applicant.id;
try {
insert(attach);
} catch(System.DMLException e) {
ApexPages.addMessages(e);
return null;
}
}
PageReference p = Page.Confirmpage;
p.setRedirect(true);
return p;
}
}
[/JAVA]
Visualforce Page:
[HTML]
<apex:page standardController=”Applicant__c” extensions=”status”>
<apex:form >
<table>
<tr>
<td>Applicant Name </td>
<td><apex:inputField value=”{!Applicant__c.Name__c}”/></td>
</tr>
<tr>
<td>CV </td>
<td> <apex:inputFile accept=”doc, txt, pdf” filename=”{!fileName}” contentType=”{!contentType}” filesize=”1000″ size=”50″ value=”{!resume}”/> </td>
</tr>
<tr>
<td></td>
<td><apex:commandButton id=”submitApplicant” value=”Submit” action=”{!saveApplication}”/></td>
</tr>
</table>
</apex:form>
</apex:page>
[/HTML]
Here:
Applicant__c is a cusomt object
Attachment is a standard object and its always available in all the object and you can enable in the pagelayout section called “Notes & Attachments”

You may also like

Leave a Comment