Reputation: 628
function displayPreview(files) {
var reader = new FileReader();
var img = new Image();
reader.onload = function (e) {
img.src = e.target.result;
fileSize = Math.round(files.size / 1024);
if(fileSize>50) {
ret1=false;
alert("File size is " + fileSize + " kb");
return ret1;
} else {
var ret1 = true;
return ret1;
}
img.onload = function () {
if(this.width!="181" && this.height!="181") {
ret1=false;
alert("width=" + this.width + " height=" + this.height);
return ret1;
} else {
var ret1 = true;
return ret1;
}
console.log("width=" + this.width + " height=" + this.height+"File size is " + fileSize + " kb");
};
};
reader.readAsDataURL(files);
}
function chkform() {
var ret = false;
if (document.getElementById("file").value === "") {
console.log("empty");
} else {
var file = document.getElementById("file").files[0];
var tt=displayPreview(file);
console.log(tt+"nis");
}
return ret;
}
When a user clicks on the submit button, the form has an onsubmit="return chkform();"
, then my checkform
checks if the id name file
is empty or not.
If not, then it call the function displayPreview()
. In that function I am checking whether the size is not more than 50 and width and height is not equal to width="181px"
and height="181px"
.
I am returning ret through which I can get the information it's returning true or false
but In my checkform
I am getting UNDEFINED
... why?
Edit
Added reproduction code at JSFIddle: http://jsfiddle.net/nishit_bhardwaj/zaukV/
Upvotes: 3
Views: 6330
Reputation: 2976
Sorry I didn't work with your code but this is how you can get the filesize. After that it's easy to validate. You also could disable or hide the submit/upload-button if the filesize is incorrect:
JS:
$("input:file").change(function () {
if ($(this).val() !== "") {
var file = $('#file_select')[0].files[0];
console.log(file.size);
}
});
HTML:
<input type="file" name="file" id="file_select" />
I added something to get width and preview image too: http://jsfiddle.net/rq8nA/1/
Upvotes: 1