<?php
if(isset($_POST['submit'])) {
$first_name=$_POST['fname'];
echo 'Entered First Name = '.$first_name;
}
?>
<html>
<form method="post" enctype="multipart/form-data" action="">
<label for="fname"> First Name: </label> <input type="text" name="fname" /> <br /><br />
<label for="file"> Select File: </label> <input type="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 18000) {
//Submit form
alert('Size is valid');
} else {
alert('pic too big');
evt.preventDefault();
}
}, false);
</script>
</html>
How to get image size of a form field (formData) in Javascript
-
30-05-2022 - |
Pregunta
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:
<form action="index.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm(this)">
<script>
function validateForm(form) {
var image_name = form.image.value;
if (image_name == null || image_name == "") {
alert('Select an image');
return false;
} else return true;
}
</script>
<label> Image (300 KB max.) <input type="file" name="image" /> </label>
<input type="submit" value="Submit" name="submit" />
</form>
Solución 2
Otros consejos
HTML5 File API supports file size check. http://www.html5rocks.com/en/tutorials/file/dndfiles/
<input type="file" id="image" />
var size = document.getElementById("image").files[0].size;
or
var size = document.getElementsByName("image")[0].files[0].size; // edit added
But its a better idea to put a server side validation for file size too.
Note : this won't work on older browsers
Also check this question :
Detecting file upload size on the client side? and
Stopping the upload process if the upload limit I chose is exceeded
Fiddle http://jsfiddle.net/wKvf8/