We will describe to you how to check file size before uploading the image on the server using jQuery.
$(function() {
$('#image').change(function() {
if (Math.round(this.files[0].size / (1024 * 1024)) > 2) {
alert('Please select image size less than 2 MB');
} else {
alert('success');
}
});
});
If the file size greater than 2MB then it will return the error messages otherwise return the success message.
#complete_code.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Tutorial</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(function() {
$('#image').change(function() {
if (Math.round(this.files[0].size / (1024 * 1024)) > 2) {
alert('Please select image size less than 2 MB');
} else {
alert('success');
}
});
});
</script>
</head>
<body>
<div class="container">
<form method="post" name="frmAdd" id="frmAdd">
<div class="form-group">
<label for="image">Image:</label>
<input type="file" name="image" class="form-control" id="image" value="">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</body>
</html>