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
ChubbyChubby 

File size validation in apex

Hi team,

I have a requirement where I have VF  page and when I choose a file to upload I need to validate file size and display error message if it is more size. After successful upload page should be redirected back to the parent object. I tried in apex and ended up with view state error. Please help to solve this
Thanks In advance.
Ajay K DubediAjay K Dubedi
Hi Chubby,
Try below code for validate file size and display error message if it is more size.
VF Page :-
<apex:inputFile size="50" filename="{!att0name}" filesize="{!att0size}" value="{!att0body}" />
Apex Class :-
if(att0name != null && att0Body != null){
 if(att0size > 5242880){ 
  //maximum attachment size is 5MB.  Show an error
  ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.Error, 'A "' + folderName0 + '" file was NOT uploaded, because it is too big (' + Decimal.valueOf(att0size/1048576).setScale(1) + ' MB): ' + att0name));
  ........
 }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
ChubbyChubby
Hi Ajay Dubedi,

I tried this solution and giving me view state error(max view state limit 170 kB exceeded). Can you help to resolve.

Thanks.