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

view state Error when upload attachements for CaseDocument Object

When upload attachements for Case Documnet Object getting View State Error .
Below scenario , getting View State Error:
Business tryng to upload PDF Documents more than 2 mb, getting this View State Error. 

When try to upload small size files more than 30+ also not getting this Error .
But, in our code we didn't mention anywhere File Size , pls let me know if required any modifications on below code :
VF Page :

<apex:page docType="html-5.0" standardController="Case" extensions="CaseDocumentFileUploadCX" title="Upload Case document">
    <apex:includeScript value="{!URLFOR($Resource.jquery)}"  />
    <apex:form id="uploadForm">

        var $jQuery = jQuery.noConflict();

            var $uploadNameInput = $jQuery('[id$="uploadFileName"]');
            //$uploadNameInput.prop('readonly', true);

            $jQuery('[id$="fileUploadInput"]').on('change', function(){
                var $this = $jQuery(this);
                //$uploadNameInput.prop('readonly', false);
                //$uploadNameInput.prop('readonly', true);
        <script type="text/javascript">
        var caseDocId;
        var caseId = '{!caseId}';
        function evaluateCaseDoc() {

                function(result1, event){
                    caseDocId = result1;
                        function(result2, event){
                            if(result2 === 'Document Upload SUCCESSFUL!'){
                        {escape: true}
                {escape: true}
        <!--<apex:actionFunction name="createCaseDoc" action="{!evaluate}" />-->
        <apex:actionFunction name="reupload" action="{!reupload}" />
        <apex:actionFunction name="loadCaseDoc" action="{!loadCaseDoc}" />
        <apex:outputPanel id="showstate"/>
        <apex:pageBlock id="filePageBlock" >
            <apex:pageMessages />
            <apex:pageBlockSection columns="1" title="File selection" id="fileSelection" >
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="{!$ObjectType.CaseDocument__c.Fields.FilePath__c.Label}" />
                    <apex:inputFile value="{!fileUpload.body}" filename="{!}" id="fileUploadInput" fileSize="{!caseDoc.FileSize__c}" contentType="{!caseDoc.MimeType__c}" style="width:100%;height:20px;" />
        <apex:pageBlock id="fileSelectionDetails" >
            <apex:pageBlockSection columns="1" title="File upload details">
                <apex:inputField value="{!caseDoc.Name}" label="{!$ObjectType.CaseDocument__c.Fields.Name.Label}" id="documentLabel" required="true" style="width:50%;" />
                <apex:inputText value="{!uploadFileName}" label="File name" id="uploadFileName" style="width:50%;" />
                <apex:inputField value="{!caseDoc.MimeType__c}"  rendered="false" label="{!$ObjectType.CaseDocument__c.Fields.MimeType__c.Label}" style="width:50%;"  />
                <apex:inputField value="{!caseDoc.BusinessCode__c}" style="width:50%;" />
                <apex:inputField value="{!caseDoc.CaseId__c}" label="{!$ObjectType.CaseDocument__c.Fields.CaseId__c.Label}" id="fileUploadCase" style="width:50%;"  />
            <apex:commandButton action="{!showCheckOpen}" value="Upload" />
        <apex:outputPanel id="showFileOpenPopUp">
          <apex:outputPanel styleClass="popupBackground" layout="block" rendered="{!showFileOpenPopUp}"/>
            <apex:outputPanel styleClass="custPopup overlayDialog cssDialog inlineEditDialog" style="display:block; visibility:visible;" layout="block" rendered="{!showFileOpenPopUp}">
              <div class="topRight">
                <div class="topLeft">
              <br />
              <apex:outputPanel id="msgLabelClass" rendered="{!showFileOpenPopUp}">
                  <div id="msg">{!$Label.CheckFileOpenDialogMessage}</div>
                  <br />
                  <br />
              <div class="buttons zen" style="margin-left: 100px; ">
                 <input id = "okuploadbtn" class="btn" width="20px" type="button" value="{!$Label.CheckFileOpenDialogOkButton}" onclick="evaluateCaseDoc();return false; "  />
                 <input id = "donebtn" style="display:none;" class="btn" width="20px" type="button" value="{!$Label.CheckFileOpenDialogOkButton}" onclick="'/'+caseDocId,'_self');"  />
                <input id = "retrybtn" style="display:none;" class="btn" width="20px" type="button" value="{!$Label.CheckFileOpenDialogOkButton}" onclick="'/apex/CaseDocumentFileUpload?id='+caseId,'_self');"  />


      [id$='msgLabelClass'] {
         display: inline;        

      [id$='msgLabelClass'] > label {
         margin-left: 10px;
        block-width: 260px;
         display: inline-block;

      [id$='msgLabelClass'] + table {
         margin-left: 10px;
         display: inline;
         vertical-align: middle;
         width: auto;

         background-color: white;
         z-index: 100;
         left: 50%;
         position: absolute;
         /* These are the 3 css properties you will need to change so the popup 
            displays in the center of the screen. First set the width. Then set 
            margin-left to negative half of what the width is. You can add 
            the height property for a fixed size pop up if you want.*/
         width: 300px;
         height: 130px;
         margin-left: -250px;
         padding-bottom: 15px;

      .custPopup h2 {
                margin-right: 30px;
                opacity: 0.20;
                filter: alpha(opacity = 20);
                position: absolute;
                width: 100%;
                height: 100%;
                top: 0;
                left: 0;
                z-index: 99;

Apex class:
 * @description Extension controller class for Case Document file upload functionality

global with sharing class CaseDocumentFileUploadCX {
    public Document fileUpload {get;set;}
    public String uploadFileName {get;set;}
    public CaseDocument__c caseDoc {get;set;}
    public Case currentCase {get;set;}
    public Integer fileSize {get;set;}
    public String jsonString {get;set;}
    //19.JAN.2015 Yogesh Gupta, NYLIM  Added new Dialog
    public Boolean showFileOpenPopUp{get;set;}
    public String caseDocId {get;set;}
    public String caseId {get;set;}
    private boolean isSuccess;

    private static String injectHeader = ' DMS Document Maintenance (From Case Document)'; 
    private static String injectTempHeader = ' DMS Document Maintenance Temp (From Case Document)';
    private static Set<String> injectStates = new Set<String>{'5.4.a'};
    private static Set<String> injectTempStates = new Set<String>{'4.2.a','4.1.a','5.4.b'};

    global CaseDocumentFileUploadCX(ApexPages.StandardController controller) {
        currentCase = (Case) controller.getRecord();
        caseId  = currentCase.Id;
        fileUpload = new Document();
        uploadFileName = '';
        fileSize = 0;
        caseDoc = new CaseDocument__c();
        caseDoc.CaseId__c = currentCase.Id;
        caseDoc.MimeType__c = '';
        isSuccess = false;

    global static String evaluate(String jsonString, String uploadFileName ){
        PageReference newPage = null;
        System.debug('uploadFileName ::: ' + uploadFileName);
        String caseDocId;
         CaseDocument__c caseDoc = (CaseDocument__c) JSON.deserialize(jsonString, CaseDocument__c.class);
        if (uploadFileName != null && uploadFileName != '') {
            // Fetch file upload settings for the current user's profile
            FileUploadSettings__c fileUploadSettings = FileUploadSettings__c.getInstance(UserInfo.getProfileId());
            if (fileUploadSettings == null) {
                fileUploadSettings = FileUploadSettings__c.getOrgDefaults();
            // Build the file path
            Id uid = UserInfo.getUserId();
            List<String> userFields = new List<String>{
            String queryString = CS_UtilSObject.buildQuery(Schema.SObjectType.User, userFields);
            queryString += 'WHERE Id = :uid';
            User u = Database.query(queryString);
            //User u = [SELECT Id, FederationIdentifier FROM User WHERE Id = :uid];
            if (u != null) {
                caseDoc.FilePath__c = fileUploadSettings.get('NetworkFolderRootPath__c') + '\\' + u.FederationIdentifier + '\\' + uploadFileName;
            } else {
                ApexPages.Message errMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'User not found');
            try {
                CaseDocumentTrigger_Handler.runAfterInsert = false;
                CaseDocumentTrigger_Handler.runAfterUpdate = false;
                insert caseDoc;
                caseDocId = caseDoc.Id;
                System.debug('* ** *** insert ' + caseDocId);
                newPage = New PageReference('/apex/CaseDocumentFileUpload2?id=' +;
            } catch (Exception e) {
                //ApexPages.Message errMsg = new ApexPages.Message(ApexPages.Severity.FATAL, e.getMessage());
                System.debug('Error ::: ' + e);
        } else {
            ApexPages.Message errMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Please upload a document');

        return caseDocId;
    public PageReference showCheckOpen(){
        showFileOpenPopUp = true;
        jsonString = JSON.serialize(caseDoc);
        fileUpload = new Document();
        caseDoc = new CaseDocument__c();
        return null;
    global static String executeRequest(String caseDocId) {
            System.debug('* ** *** executeRequest');
            System.debug('* ** *** caseDocId ' + caseDocId);
            List<CaseDocument__c> caseDocList = [SELECT Id, IntegrationState__c, FilePath__c  FROM CaseDocument__c WHERE Id = :caseDocId LIMIT 1];
                return 'UPLOAD FAILURE: An unexpected error has occured. Please try to upload document again. If you continue to experience difficulties, please contact your system administrator.';
            CaseDocumentTrigger_Handler.runAfterInsert = false;
            CaseDocumentTrigger_Handler.runAfterUpdate = false;
            CaseDocumentTrigger_Handler.runBeforeUpdate = false;
            CaseDocument__c  caseDoc = caseDocList.get(0);
                if(!Test.isRunningTest()) CaseDocumentTrigger_Handler.executeRequests(new Set<String>{},injectHeader,true); 
                if(!Test.isRunningTest()) CaseDocumentTrigger_Handler.executeRequests(new Set<String>{},injectTempHeader,true); 
            PageReference newPage;
            caseDoc = [SELECT Id, CaseId__c, DMSInject_Code__c, DMSInject_Status__c FROM CaseDocument__c WHERE Id = :caseDocId];
            if(caseDoc.DMSInject_Status__c  == 'SUCCESS'){
                boolean isSuccess  = true;
                return 'Document Upload SUCCESSFUL!';
                delete caseDoc;
                if(caseDoc.DMSInject_Code__c == '01'){
                    return 'DOCUMENT NOT FOUND: Please ensure that the document that you are trying to upload is located in the proper location and try again.';
                    return 'UPLOAD FAILURE: An unexpected error has occured. Please try to upload document again. If you continue to experience difficulties, please contact your system administrator.';
            return 'UPLOAD FAILURE: An unexpected error has occured. Please try to upload document again. If you continue to experience difficulties, please contact your system administrator.';
            //return  New PageReference('/apex/CaseDocumentFileUpload2?id=' +;

   public PageReference reupload(){
        PageReference  newPage  =  New PageReference('/apex/CaseDocumentFileUpload?id=' + caseId);
        return newPage;  
    public PageReference loadCaseDoc(){
        PageReference  newPage  = New PageReference('/' + caseDocId);
        return newPage;  
    public PageReference showFileOpenPopUpPanel(){
        return null;

    public PageReference hideFileOpenPopUpPanel(){
        showFileOpenPopUp = False;
        return null;

Pls let me know any one have idea, how to fix View State error when upload large files for CaseDocumnet Object

ShirishaShirisha (Salesforce Developers) 


It is difficult to provide you the causes of the errors by seeing the code as it could be because of the components you used or the SOQL queries which are returning huge records.

So,I would suggest you to go through the below document ( for the causes and how to troubleshoot the issue.

You need to enable developer Mode to check which components are using the high view.


Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri