Save an attachment in APEX

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.

/*****Controler*****/

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

/**Controller**/
<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>

You can try it with your own object and particular fields.

Comments

  1. We're having trouble talking to yahoo.com.
    Either login to Facebook directly or try again later.

    ReplyDelete
  2. but I think the Name__c value is null and the the field name value is the id of custom object

    ReplyDelete
  3. Is there a way to validate if the file is chosen or not - the validation error should be on page and not as a pop-up? Can we do it?

    ReplyDelete
  4. How to write test class for this code?Please help.

    ReplyDelete
  5. Insert Attachment successfully . But the form accept 'HTML,TAR ,etc' files
    "accept="doc, txt, pdf" is not working !!

    ReplyDelete

Post a Comment

Popular posts from this blog

Parameter passing using Javascript+actionFunction in visualforce

Displaying pop-up summaries on hover in visualforce