<apex:page standardController="Account" extensions="FileUploadController">
<apex:sectionHeader title="Account" subtitle="Account Attachments"/>

<apex:form >
<apex:pageMessages />
<apex:pageBlock title="Upload a File">

<apex:pageBlockButtons >
<apex:commandButton action="{!upload}" value="Attach"/> 

<apex:pageBlockSection showHeader="false" columns="2" id="block1">

<apex:pageBlockSectionItem >
<apex:outputLabel value="File" for="file"/>
<apex:inputFile value="{!document.body}" filename="{!document.name}" id="file"/>




public with sharing class FileUploadController { 
    public FileUploadController(ApexPages.StandardController controller) {


    public Attachment document { 
    get { 
        if (document == null) 
        document = new Attachment(); 
    return document; 
public PageReference upload() {

   document.OwnerId = UserInfo.getUserId();
   document.ParentId = ApexPages.currentPage().getParameters().get('id'); // the record the file is attached to
   document.IsPrivate = true;
//document.AuthorId = UserInfo.getUserId(); 
//document.FolderId = UserInfo.getUserId(); // put it in running user's folder 
try { 
insert document;
} catch (DMLException e) { 
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading file')); 
return null; 
} finally { 
document.body = null; 
document = new Attachment(); 
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'File uploaded successfully')); 
return null; 

Its simple. if you are coming from account detail page then get Account Id in a variable and redirect that using Pagereference method.

public Id accountId;
public FileUploadController(ApexPages.StandardController controller) {
          accountId = controller.getId();

public PageReference upload() {

// your code here
if(accountId != null)
   return new Pagereference('/'+accountId );
return  new Pagereference('/001');


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.