Any idea how to get size in bytes of an image within a validating javascript function so that user will be prompted to pick a valid image size. I have seen other answers which handle this out of the form logic, but I want to know if I can get the size within the validation javascript function. Thanks
Here is my Form related code:
JavaScript
x
14
14
1
<form action="index.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm(this)">
2
<script>
3
function validateForm(form) {
4
var image_name = form.image.value;
5
if (image_name == null || image_name == "") {
6
alert('Select an image');
7
return false;
8
} else return true;
9
}
10
</script>
11
<label> Image (300 KB max.) <input type="file" name="image" /> </label>
12
<input type="submit" value="Submit" name="submit" />
13
</form>
14
Advertisement
Answer
JavaScript
1
29
29
1
<?php
2
if(isset($_POST['submit'])) {
3
$first_name=$_POST['fname'];
4
echo 'Entered First Name = '.$first_name;
5
}
6
?>
7
<html>
8
9
<form method="post" enctype="multipart/form-data" action="">
10
<label for="fname"> First Name: </label> <input type="text" name="fname" /> <br /><br />
11
<label for="file"> Select File: </label> <input type="file" id="file" />
12
<input type="submit" name="submit" value="Submit" />
13
</form>
14
15
<script>
16
document.forms[0].addEventListener('submit', function( evt ) {
17
var file = document.getElementById('file').files[0];
18
19
if(file && file.size < 18000) {
20
//Submit form
21
alert('Size is valid');
22
} else {
23
alert('pic too big');
24
evt.preventDefault();
25
}
26
}, false);
27
</script>
28
</html>
29