How to validate uploading file size using javascript?

How to validate Maximum Size upload file?

Demo Example

File name : index.php

<input type="file" id="file_upload" name="file_upload" class="form-control" onchange="Validatefile(this.id,this.value)" >
<span class="required" aria-required="true">(Only PDF,JPG,PNG files are allowed, File Size Allowed 5MB)</span>
<span class="required" id="file_upload_error" aria-required="true"></span>


<script>
function Validatefile(id,val){

var image =$('#'+id).val();

if(image!=''){

var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.jpeg|\.JPEG|\.pdf)$/)){
$('#'+id).focus();
alert("Invalid file extension, Only jpg,jpeg,png,bmp,pdf files are Allowed");
$('#'+id).val('');
return false;
}
var img = document.getElementById(id);
var fsize=img.files[0].size;
const file = Math.round((fsize / 1024));
if(file >= 5000) {
alert("File size too large, Please select a file less than 5mb");
$('#'+id).val("");
return false;
}
return true;




}
}
</script>

Demo Example

Demo Example

File name : index.php


Demo Example 2

File name : index.php


Demo Example 2

Output :-


How to Get File Name, Size, Type Count in jQuery

File name : index.php

<html><head></head><body><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><br /><input id="fUpload" multiple type="file" />
<ul id="ulList"></ul><input id="btnShow" type="button" value="Show" /><br />
<script>
$("#btnShow").on('click', function() {
$("#ulList").empty();
var fp = $("#fUpload");
var lg = fp[0].files.length; // get length
var items = fp[0].files;
var fragment = "";

if (lg > 0) {
for (var i = 0; i < lg; i++) {
var fileName = items[i].name; // get file name
var fileSize = items[i].size; // get file size
var fileType = items[i].type; // get file type

// append li to UL tag to display File info
fragment += "<li>" + fileName + " (<b>" + fileSize + "</b> bytes) - Type :" + fileType + "</li>";
}

$("#ulList").append(fragment);
}
});

</script></body> </html>





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here