I have used simple code to upload File.
Now My page is giving me the following error:
Maximum view state size limit (135KB) exceeded. Actual view state size for this page was 838.719KB
- I have tried making all variables Transient
- Removed PageBlock
Instead of coming on this error page - I want to show an Error Message like "Too big File. Upload files having size less than 2 MB."
How can I achieve this. Any Help or Any other suggestions ?
Visualforce Code :
<apex:page standardController="Contact" showHeader="true" extensions="PhotoUploadController">
<apex:sectionHeader title="Upload photo of {!obj.name}"/>
<apex:form >
<apex:pagemessages />
<br/>
<apex:outputText ><b>1. Select the photo</b></apex:outputText><br/><br/>
<apex:outputText > Click the <b>"Choose File" </b>to find the photo.</apex:outputText><br/><br/>
<apex:inputFile title="Upload Photo" contentType="{!objAttach.ContentType}" value="{!objAttach.body}" fileName="{!objAttach.name}" id="file"></apex:inputFile>
<br/><br/><br/>
<apex:outputText><b>2. Upload Photo</b></apex:outputText><br/><br/>
<apex:outputText >Click the <b>"Upload Photo"</b> button.</apex:outputText><br/><br/>
<apex:commandButton value="Upload Photo" action="{!savePhoto}"/><br/><br/>
</apex:form>
</apex:page>
Controller Code :
public with sharing class PhotoUploadController {
public Attachment objAttach{ get {
if(objAttach== null)
objAttach= new Attachment();
return objAttach;
}
set;
}
transient Public Contact obj{get;set;}
public PhotoUploadController(ApexPages.StandardController controller){
objAttach=new Attachment();
obj= (Contact)controller.getRecord();
if(obj.id!=null){
obj= [select id,name from Contact where id=:obj.id];
}
}
public pageReference savePhoto(){
try {
transient String contentType=objAttach.ContentType;
if(contentType == 'image/jpeg' || contentType== 'image/png' ){
if(objAttach.body!=null && objAttach.name!=null){
objAttach.parentId=obj.id;
try {
upsert objAttach;
obj.Image_URL__c=URL.getSalesforceBaseUrl().toExternalForm()+'/servlet/servlet.FileDownload?file='+objAttach.id;
objAttach =null;
upsert obj;
obj=null;
}catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
return null;
}finally {
objAttach.body = null;
}
}
return new pagereference('/'+obj.id);
}else{
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please, Upload image file with extension .JPG or .PNG'));
return null;
}
}
catch(Exception e){
ApexPages.addMessages(e);
return null;
}
}
}
transient
is theAttachment
member,objAttach
. This is where the large binary data is stored when the form is posted and then this data is serialized into the viewstate.