file upload size limit validation in javascript

Today, We want to share with you file upload size limit validation in javascript.In this post we will show you File upload size validation using jQuery with demo, hear for multiple file upload size limit validation in javascript we will give you demo and example for implement.In this post, we will learn about How to check file input size with an example.

Validation of file size while uploading using JavaScript / jQuery

var uploadField = document.getElementById("file");

uploadField.onchange = function() {
    if(this.files[0].size > 307200){
       alert("File is too big!");
       this.value = "";
    };
};

jquery get file size in kb

In this example if we upload File which size is greater than 500kb it give a message.
Example 1: index.html

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
	$("#mainDPImg").change(function(){
		$("#print_exeception").html("");
		$(".profile_doc_set1").css("border-color","#F0F0F0");
		var file_size = $('#mainDPImg')[0].files[0].size;
		if(file_size>500000) {
			$("#print_exeception").html("<p style='color:#FF0000'>File size is greater than 500kb</p>");
			$(".profile_doc_set1").css("border-color","#FF0000");
		return false;
		}
		return true;
	});
});
</script>
</head>
<body>
<span id="print_exeception"></span>
<input type="file" id="mainDPImg" name="profile_doc_set1" class="profile_doc_set1">
</body>
</html>

File size validation before upload

Example 2:

var maxSizeLimit = '1024';
function fileSizeValidate(profilecontent) {
	 if (profilecontent.files && profilecontent.files[0]) {
                var fsize = profilecontent.files[0].size/1024;
                if(fsize > maxSizeLimit) {
                	 alert('Maximum file size exceed, This file size is: ' + fsize + "KB");
                	 return false;
                } else {
                	return true;
                }
     }
 }

Image extension validation before upload

Example 3:

var validExt = ".png, .gif, .jpeg, .jpg";
function fileExtValidate(profilecontent) {
 var filePath = profilecontent.value;
 var getFileExt = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
 var check = validExt.indexOf(getFileExt);
 if(check < 0) {
 	alert("Sorry, This file is not allowed, please upload valid file.");
 	return false;
  } else {
  	return true;
  }
}

I hope you get an idea about Get File Size before Uploading in JavaScript and jQuery.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.