6

I have a page with apex:commandButton which calls javascript to validate image selected and a method from controller to upload image. For some reason before javascript is done executing, controller method is called and if a huge image is selected I can view state error

Maximum view state size limit (135KB) exceeded

Here is my code. Is there a workaround or way to optamize this code?

<apex:page controller="MyController" contentType="text/html" readonly="false">
    <head>
        <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" />
    </head>
    <body>
        <script type="text/javascript">
            j$ = jQuery.noConflict();
            function FileSize() {
                alert('sdfsdfsd');
                var fileInput = $('#idFileUpload');
                var fileName = fileInput.get(0).files[0].name;
                $("[id$='hdnDocName']").val(fileName);
                if(fileInput.get(0).files.length)
                {
                    var fileSize = fileInput.get(0).files[0].size; // in bytes
                    if(fileSize>100000)
                    {
                        alert('file size is more than 100KB');
                        return false;
                    }
                    else
                    {                       
                        alert('file size is less than 100KB');
                        return true;
                    }
                }
                else
                {
                    alert('Please select the file to upload');
                    return false;
                }
            }
        </script>
        <apex:form id="upload-form">
            <apex:pageMessages />
            <br/>
            <apex:outputPanel rendered="{!accountID != '' && accountName != ''}">
                <apex:inputHidden id="hdnDocName" value="{!filename}"/>
                <h2>Account Name: <label>{!accountName}</label></h2>
                <br/><br/>
                Please select image (max 100KB):
                <apex:inputFile value="{!doc.body}" filename="{!doc.name}" id="idFileUpload" accept="image/*" fileSize="{!fileSize}"/>
                <br/><br/>
                <apex:commandButton value="Upload" onClick="if (FileSize() === false) { return false; }" action="{!SaveMyFile}"/>   
            </apex:outputPanel>
            <apex:outputPanel rendered="{!accountID == ''}">
                No valid account selected
            </apex:outputPanel>
        </apex:form>
    </body>
</apex:page>

Apex Class:

public Pagereference SaveMyFile()
{
    if (fileSize == 0)
    {
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Invalid file: Please upload either GIF, JPG, JPEG or PNG file'));
        return null;
    }
    if (fileSize > 100000)
    {
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Invalid file: File size exceeds 100KB'));
        return null;
    }
    filename = doc.Name;
    if (filename != null)
    {
        if (filename.toLowerCase().endsWith('.jpeg'))
        {
            doc.Type = 'jpeg';
            doc.ContentType = 'image/jpeg';
        }
        else if (filename.toLowerCase().endsWith('.jpg'))
        {
            doc.Type = 'jpg';
            doc.ContentType = 'image/jpg';
        }
        else if (filename.toLowerCase().endsWith('.png'))
        {
            doc.Type = 'png';
            doc.ContentType = 'image/png';
        }
        else if (filename.toLowerCase().endsWith('.gif'))
        {
            doc.Type = 'gif';
            doc.ContentType = 'image/gif';
        }
        else
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Invalid file: Please upload either GIF, JPG, JPEG or PNG file'));
            return null;
        }
        doc.AuthorId = UserInfo.getUserId();
        doc.Name = accountName;
        //doc.body = fileImage;
        doc.IsPublic = true;
        Schema.SObjectField upsertField = Document.Name;

        doc.FolderId = UserInfo.getUserId();
        try
        {
            //insert doc;
            Database.upsert(doc, upsertField, false);
            //getCurrentImage(accountID);
        }
        catch (DMLException e)
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading file'));
            return null;
        }
        finally
        {
            doc.body = null; // clears the viewstate
            doc = new Document();
        }       
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'File uploaded successfully'));
    }
    return null;
}

public Document doc
    {
        get 
        {
            if (doc == null)
            {
                doc = new Document();
                doc.Name = accountName;
                doc.description = '';
                doc.keywords = '';
            }
            return doc;
        }
        set;
    }
  • Try using "oncomplete" attribute instead of action on commandbutton – Anurag A May 31 '16 at 20:09
  • Can you post your apex class? – Anurag A May 31 '16 at 20:11
  • added class method – user569925 May 31 '16 at 20:14
  • did you check the view state map and see what variables are hold more kb? – Anurag A May 31 '16 at 20:16
  • you can enable it from your user settings, check "Show View State in Development Mode" to true – Anurag A May 31 '16 at 20:17
5

Make the variable "doc" static to avoid view state error

1

I believe the issue lies in the line var fileInput = $('#idFileUpload');. As you have used <apex:inputFile the id attribute will become something like j_id0:upload-form:idFileUpload in the final html.

You have to use jQuery partial selector .

var fileInput = $('[id$=idFileUpload]')

Or Salesforce $Component method to select the file input field.

var fileInput = document.getElementById('{!$Component.upload-form.idFileUpload}');

Also please make the id upload-form to upload_form. Many a times javascript fails if there is an hyphen in a id attribute.

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.