Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,
I want to validate an file to be uploaded if size is more then 5 M.B. on button
click event using java script.
Please help me on this.

Thanks in Advance.
Posted

1 solution

Hi Kapil,

Let us say that you FileUpload control has id as "FileUpload1".
You can use the following javascript for this:
JavaScript
function validateFileSize() {
      var uploadControl = document.getElementById('<%= FileUpload1.ClientID %>');
      if (uploadControl.files[0].size > 1048576*5) {
          alert('Maximum size allowed is 5 MB');
          return false;
       }
       else {
           return true;
        }
      }


Also, add this to you FileUpload Control,
onchange="validateFileSize();"


Hope this works for you !! :)

Regards,
Praneet
 
Share this answer
 
v2
Comments
[no name] 5-Nov-14 1:51am    
Please check the calculation for file size once.
kapil0411 5-Nov-14 2:04am    
Hi Praneet,
Thanks for your response.
but i am getting java script error in line :-
if (uploadControl.files[0].size > 1048576*5)

kindly help me on this
[no name] 5-Nov-14 2:06am    
use this if (uploadControl.files[0].size > 1048576) {
alert('Maximum size allowed is 1 MB');
return false;
}
This should work
This will be for 1 mb. You can change this as per your needs
kapil0411 5-Nov-14 2:14am    
Praneet i am getting error for
"uploadControl.files[0]" it is coming as null.
[no name] 5-Nov-14 2:18am    
That code works fine for me. Can u paste your code here ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900