function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sapthagiri_186sapthagiri_186 

Uploading an attachment

Hi,

 

How can we upload a file/image using apex conroller and it has to be saved into custom objects.

 

Regards

Sapthagiri Reddy

 

bob_buzzardbob_buzzard

I've written a blog post that does this - its actually handling multiple attachments in one go but should be straightforward to adapt.

sapthagiri_186sapthagiri_186

Hi,

 

Here is the  requirement, there are 2 VF page and an apex controller.

 

When a user enters an activity and at the same times wishes to attach notes/attachment, the user is redirected to a new page wherein he gets to upload the required attachment, here the attached attachment must only get uploaded and not saved and  on clicking upload button it must be redirected to the previous page (activity entry page). 

 

Finally, upon clicking "Save" button (in the Activity Entry Page), the activity entered & the attachment must be saved to the custom object.

 

Regards

Sapthagiri Reddy

bob_buzzardbob_buzzard

Just realised I didn't post the link:

 

http://bobbuzzard.blogspot.co.uk/2011/01/uploading-multiple-attachments-via.html

 

You can download the code I used to build this - it adds attachments to the record identified on the page.

sapthagiri_186sapthagiri_186

Hi,

 

Here is the  requirement, there are 2 VF page and an apex controller.

 

When a user enters an activity and at the same times wishes to attach notes/attachment, the user is redirected to a new page wherein he gets to upload the required attachment, here the attached attachment must only get uploaded and not saved and  on clicking upload button it must be redirected to the previous page (activity entry page). 

 

Finally, upon clicking "Save" button (in the Activity Entry Page), the activity entered & the attachment must be saved to the custom object.

 

Regards

Sapthagiri Reddy

bob_buzzardbob_buzzard

The blog post has code that can be adapted for this.  Just don't write the attachment to the database until you are ready.

sapthagiri_186sapthagiri_186

Sorry mate,

 

Except for an image for multiple uploading, didn't find any code.

 

When a user clicks "Upload a File" from a page (page block), it leads to another new page, where in the user gets to attach (only upload) a file & upon clicking on "upload" here, it has to redirect to the previous page (and with me it is redirecting to a page but the required pageblock renders aren't working), where the user enters an activity and on clicking on "Save", both the activity and the attachment gets saved to the list below.

 

Regards

Sapthagiri Reddy

 

sapthagiri_186sapthagiri_186

Hey Bob,

 

I have been getting this error Maximum view state size limit (135KB) exceeded when I am uploading a file through a custom page to the Notes and Attachemnts and it only occurs if the file size is little large and gets successfully uploaded if the file size is somewhere around 50kb.

 

And when I used Transient (public transient Attachment document{get;set;}) I started getting attempt to dereference a null object error. 

 

Best Regards

bob_buzzardbob_buzzard

This sounds like you are persisting the attachment body in the viewstate between pages - that can blow the limit pretty quickly.  Can you attach it to a dummy record or similar?

sapthagiri_186sapthagiri_186

Hello Bob,

 

Here is my code,

 

document = new Attachment(); /*Defined this one in Constructor*/


/*Uploading a file*/

public transient Attachment document{get;set;}

insert ViewManagerActivity; /Where the activity gets inserted*/
Activity_ID = ViewManagerActivity.id;

document.ParentId = Activity_ID;
document.IsPrivate = true;
try
{
    if(document.name == '' || document.body == Null) /* Its here where I am getting null, i.e. both Name and body are becoming null*/
    {

 

     }
else
{
    insert document;
    attach_type = [select id,ParentId, Name from Attachment where ParentId =: Activity_ID];
    attachmentName = attach_type.Name;
}

}
catch (DMLException e)
{
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
}
finally
{
     document = new Attachment();
}

 

Best Regards

bob_buzzardbob_buzzard

You can't use transient for properties that will be set from the page. - the purpose of transient is to exclude stateless data from the viewstate. 

sapthagiri_186sapthagiri_186

Hey Bob,

 

If I am not using Transient, I am getting "Maximum view state size limit (135KB) exceeded" error and at the same time the attached file is being saved (I could see it only after refresing the page).

 

Is there any way where I could catch this "Maximum view state size limit (135KB) exceeded" exception using try/catch blocks.

 

Best Regards

bob_buzzardbob_buzzard

No, this is happening out of your hands when the controller state is converted to the view state.  I'm surprised its going with a file as small as 50kb.  I'm sure I've been able to upload much larger files than this.

sapthagiri_186sapthagiri_186

Hey Bob, 

 

Here is my code, correct me where I went wrong. There is a button in another page, which upon clicked redirects to another page and here is that page codes.

 

Visualforce Page

 

<apex:page controller="Prospective_Attachment_AC" showHeader="true" standardStylesheets="false">
<head>
<script type="text/javascript">
function SelectFile( fileUrl )
{
// window.opener.SetUrl( url, width, height, alt);
parent.SetUrl( fileUrl ) ;
}
</script>
</head>
<apex:messages title="Errors Occured" styleClass="errorMsg" style="font-family:verdana,garamond,serif;" />
<br></br><br></br>
<apex:form >
<b><apex:outputLabel style="font-size:14px;" value="File" for="file"/></b>
<apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" />
<apex:commandButton value="Save" action="{!upload}" />
<apex:commandButton action="{!cancel_upload}" value="cancel"/>
</apex:form>
<apex:pageBlock rendered="{!hasImage}" >
<img src="{!url}" width="200" height="160" />
<script>
this.onload = function()
{
SelectFile('{!url}');
}
</script>
</apex:pageBlock>
</apex:page>

 

Apex Controller 

 


public with sharing class Prospective_Attachment_AC
{
public String LeadInfo_ID,ClientInfo_ID,DeleteLeadInfo_ID,EditLeadInfo_ID,Activity_ID,LeadActivity_ID,ConvertToClient_ID;
public String MailingmanagerAssigned,ManagementAdmin;
public string DuplicateLeadName,DuplicateEmail,DuplicateClient,DuplicateClientNumber;
public integer clientnumber = 0;
Manager_Activity__c MList = new Manager_Activity__c();
User uname,uname1 ;
User UserName = new User();
String LoggedUserName = UserInfo.getUserName();
String ProfineName = UserInfo.getName();
User MailingUser = [Select Name,Email,profile.Name,Manager.Email From User where Username =: LoggedUserName limit 1];

String New_ID;
public Prospective_Attachment_AC() /*Constructor*/
{
New_ID = System.currentPageReference().getParameters().get('Id');
mgnrInfo = [select id, Date__c,Manager_Associated__c,uploadcheck__c,Expectations__c,Activity_Discreption__c,Follow_Up__r.Lead_Name__c, Follow_Up__r.Lead_Manager__c,Follow_Up__r.User__c,Follow_Up__r.User__r.Name,Follow_Up__c from Manager_Activity__c where id=:New_Id];
ViewLeadsInfo = [select id, Lead_Name__c,User__r.Name,User__c,Company_Name__c,Last_Activity_Date__c,Phone_Number__c,Approached_Through__c,Lead_Manager__c,Website__c,Technology__c,Contact_Mail_ID__c,Lead_Description__c,Status__c,Start_Date__c,End_Date__c,ClientToLead__c,
Billing_City__c, Billing_Country__c, Billing_State__c, Billing_Street__c, Billing_Zip_Code__c, Shipping_City__c, Shipping_Country__c, Shipping_State__c, Shipping_Street__c, Shipping_Zip_Code__c from Lead_Info__c where id =: mgnrInfo.Follow_Up__c];
}

public Lead_Info__c ViewLeadsInfo = new Lead_Info__c();
public Lead_Info__c getViewLeadsInfo()
{
return ViewLeadsInfo;
}
public Manager_Activity__c ViewManagerActivity = new Manager_Activity__c();
public Manager_Activity__c getViewManagerActivity()
{
return ViewManagerActivity;
}
List<Lead_Info__c> LeadDetails_List = [select Lead_Name__c,User__r.Name,User__c,Contact_Mail_ID__c,Last_Activity_Date__c,Company_Name__c,Phone_Number__c,Approached_Through__c,Lead_Manager__c,Website__c,Technology__c,Lead_Description__c,Status__c,Start_Date__c,End_Date__c,
Billing_City__c, Billing_Country__c, Billing_State__c, Billing_Street__c, Billing_Zip_Code__c, Shipping_City__c, Shipping_Country__c, Shipping_State__c, Shipping_Street__c, Shipping_Zip_Code__c from Lead_Info__c order by CreatedDate desc];
public List<Lead_Info__c> getLeads_Info()
{
return LeadDetails_List;
}
List<Manager_Activity__c> ManagerActivity_List = [select id,Date__c,uploadcheck__c,Manager_Associated__c,Expectations__c,Activity_Discreption__c,Follow_Up__r.Lead_Name__c, Follow_Up__r.Lead_Manager__c,Follow_Up__r.User__c,Follow_Up__r.User__r.Name,Follow_Up__c from Manager_Activity__c where Follow_Up__c =: LeadInfo_ID order by CreatedDate asc];
public List<Manager_Activity__c> getManager_Activity()
{
return ManagerActivity_List;
}
public void ViewInfo()
{
Activity = true;
Leads_Table = true;
View_LeadsInfo = true;
HideNewLead_Button = true;
Enter_Activity = true;
ManagerActivity_List = [select id, Date__c,Manager_Associated__c,uploadcheck__c,Expectations__c,Activity_Discreption__c,Follow_Up__r.Lead_Name__c, Follow_Up__r.Lead_Manager__c,Follow_Up__r.User__c,Follow_Up__r.User__r.Name,Follow_Up__c from Manager_Activity__c where Follow_Up__c =:ViewLeadsInfo.id];
ViewManagerActivity.Date__c = System.Today();
ViewManagerActivity.Manager_Associated__c = ViewLeadsInfo.User__r.Name;
Map<String,String> attIdMap = new Map<String,String>();
Map<String,String> attNameMap = new Map<String,String>();
for(Attachment att : [select Id, ParentId, name from Attachment])
{
attIdMap.put(att.ParentId,att.Name);
attNameMap.put(att.ParentId,att.Id);
}
for(Manager_Activity__c ManagerAtt : ManagerActivity_List)
{
InnerClass ic =new InnerClass();
ic.ManageActRec = ManagerAtt;
//ic.AttName = attachmentName;
ic.AttName = attIdMap.get(ManagerAtt.Id);
ic.Attid = attNameMap.get(ManagerAtt.Id);
innerlist.add(ic);
}
}
public void ViewLeadsDetails()
{
LeadInfo_ID = System.currentPageReference().getParameters().get('LeadId');
ViewLeadsInfo = [select id, Lead_Name__c,User__r.Name,User__c,Company_Name__c,Last_Activity_Date__c,Phone_Number__c,Approached_Through__c,Lead_Manager__c,Website__c,Technology__c,Contact_Mail_ID__c,Lead_Description__c,Status__c,Start_Date__c,End_Date__c,ClientToLead__c,
Billing_City__c, Billing_Country__c, Billing_State__c, Billing_Street__c, Billing_Zip_Code__c, Shipping_City__c, Shipping_Country__c, Shipping_State__c, Shipping_Street__c, Shipping_Zip_Code__c from Lead_Info__c where id =: LeadInfo_ID];

if(ViewLeadsInfo.ClientToLead__c == true)
{
ConvertToClientButton = false;
ViewInfo();
}
else
{
ConvertToClientButton = true;
ViewInfo();
}
}

public Class InnerClass /*Inner Class */
{
public Manager_Activity__c ManageActRec{get;set;}
public String AttName{get;set;}
public String AttID{get;set;}
public Integer RecUniqId {get;set;}
}
Integer recCount = 1;
public List<InnerClass> Innerlist = new List<InnerClass>(); /* Inner Class List */
public List<InnerClass> getinnerlistRec()
{
return Innerlist;
}

public String attachmentName{get; set;}
Attachment attach_type = new Attachment();

Manager_Activity__c mgnrInfo = new Manager_Activity__c();

public transient Attachment att = new Attachment();
public string id;
public string fileName
{
get;set;
}
public Transient Blob fileBody
{
get;set;
}

public void upload()
{
mgnrInfo = [select id, Date__c,Manager_Associated__c,uploadcheck__c,Expectations__c,Activity_Discreption__c,Follow_Up__r.Lead_Name__c, Follow_Up__r.Lead_Manager__c,Follow_Up__r.User__c,Follow_Up__r.User__r.Name,Follow_Up__c from Manager_Activity__c where id=:New_Id];
Activity_ID = mgnrInfo.id;
uname1 = [select id, Name from User where Name=: mgnrInfo.Manager_Associated__c];
ViewLeadsInfo.Last_Activity_Date__c = System.Today();
update ViewLeadsInfo;
Activity = true; /*Boolean variable*/
User MailManager2 = [select id,Name,Email from User where Name=: mgnrInfo.Manager_Associated__c];
MailingmanagerAssigned = MailManager2.Email;
try
{
att = new Attachment();
att.Body = this.fileBody;
att.Name = this.fileName;
System.debug(att.Body+'&&&'+att.Name);
att.ParentId = Activity_ID;
this.fileBody = null;
insert att;
id = att.id;
attach_type = [select id,ParentId,Body, Name from Attachment where ParentId =: Activity_ID];
attachmentName = attach_type.Name;

InnerClass ic = new InnerClass();
ic.ManageActRec = MList;
ic.AttName = attachmentName;
ic.Attid = attach_type.id;
ic.RecUniqId = recCount;
recCount++;
innerlist.add(ic);
}

catch (DMLException e)
{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
}
finally
{
att = new Attachment();
}
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));

AssignedManagerMail();
ManagerActivity_List = [select id, Date__c,uploadcheck__c,Manager_Associated__c,Expectations__c,Activity_Discreption__c,Follow_Up__r.Lead_Name__c,Follow_Up__r.Lead_Manager__c,Follow_Up__r.User__c from Manager_Activity__c where Follow_Up__c =:ViewLeadsInfo.id];
}

pagereference pageref3 = new pagereference('/apex/Prospective_Clients_VP');
public pagereference Cancel_upload() /* Cancel uploading the file */
{
Leads_Table = true;
Activity = true;
Enter_Activity = true;
View_LeadsInfo = true;
HideNewLead_Button = true;
pageref3.setRedirect(true);
return page.Prospective_Clients_VP;
}

/*Boolean Methods*/
public boolean Leads_Table{get; set;}
public boolean View_LeadsInfo{get; set;}
public boolean Activity{get; set;}
public boolean NewLeadInfo{get; set;}
public boolean HideNewLead_Button{get; set;}
public boolean Cancel_ViewLeadInfo{get; set;}
public boolean Edit_LeadDetails{get; set;}
public boolean Enter_Activity{get; set;}
public boolean ViewActivityInfo{get; set;}

public boolean ProjectDetails{get; set;}
public boolean ConvertToClientButton{get; set;}
public boolean hasImage {get; set;}
public boolean displayactivity {get; set;}

public String url {get; set;}
}

 

Best Regards

sapthagiri_186sapthagiri_186

Hi Bob,

 

I did find your multi attachment code helpful nad will fill my requirement. But I am getting a few errors while using your code and here are the errors:

 

1. No such column 'Description' on entity 'Attachment'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.MultiAttachmentController.cls

 

ANd if I had to attach the attachment to an custom object, where shall I change the sobjId.

 

Best Regards

SFDummySFDummy

I am getting same view state error "Maximum view state size limit (135KB) exceeded"

how did you solve the problem?