In this article I will explain how to check (validate) File (Image) size before upload using JavaScript and jQuery.
HTML5 allows developers to access the file contents and details using JavaScript and jQuery and hence in browsers that support HTML5 one can easily determine the size of the File.
For browsers that don’t support HTML5 have to use jQuery Flash plugins like Uploadify.
Determining the size of the file using JavaScript and HTML5
The following HTML markup consists of an HTML FileUpload and a Button. When the button is clicked, a function named Upload is executed.
Inside this function, first a check is performed to verify whether the browser supports HTML5 File API. If the browser supports HTML5 File API then the size of the file is determined and the displayed.
<
input
type="file" id="fileUpload" />
<
input
type="button" value="Upload" onclick="Upload()" />
<
script
type="text/javascript">
function Upload() {
var fileUpload = document.getElementById("fileUpload");
if (typeof (fileUpload.files) != "undefined") {
var size = parseFloat(fileUpload.files[0].size / 1024).toFixed(2);
alert(size + " KB.");
} else {
alert("This browser does not support HTML5.");
}
}
</
script
>
Determining the size of the file using jQuery and HTML5
The following HTML markup consists of an HTML FileUpload and a Button. When the button is clicked, a jQuery click event handler is executed.
Inside the click event handler, first a check is performed to verify whether the browser supports HTML5 File API. If the browser supports HTML5 File API then the size of the file is determined and the displayed.
<
input
type="file" id="fileUpload" />
<
input
type="button" id="upload" value="Upload" />
<
script
type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<
script
type="text/javascript">
$(function () {
$("#upload").bind("click", function () {
if (typeof ($("#fileUpload")[0].files) != "undefined") {
var size = parseFloat($("#fileUpload")[0].files[0].size / 1024).toFixed(2);
alert(size + " KB.");
} else {
alert("This browser does not support HTML5.");
}
});
});
</
script
>