Reputation: 79
I want to validate the image size and extension before uploading an image .I have code for image extention and I want to restrict the size of the image. Here is the code for image extension:
function ValidateFileUpload() {
var fuData = document.getElementById('fileChooser');
var FileUploadPath = fuData.value;
if (FileUploadPath == '') {
alert("Please upload an image");
} else {
var Extension = FileUploadPath.substring(
FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
if (Extension == "gif" || Extension == "png" || Extension == "bmp"
|| Extension == "jpeg" || Extension == "jpg") {
if (fuData.files && fuData.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(fuData.files[0]);
}
}
else {
alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
}
}
}
HTML code
<input type="file" name="image" id="fileChooser" style="height:28px; width:175px;" onchange="return ValidateFileUpload()">
Upvotes: 5
Views: 41013
Reputation: 4503
function ValidateFileUpload() {
var fuData = document.getElementById('fileChooser');
var FileUploadPath = fuData.value;
if (FileUploadPath == '') {
alert("Please upload an image");
} else {
var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
if (Extension == "gif" || Extension == "png" || Extension == "bmp"
|| Extension == "jpeg" || Extension == "jpg") {
if (fuData.files && fuData.files[0]) {
var size = fuData.files[0].size;
if(size > MAX_SIZE){
alert("Maximum file size exceeds");
return;
}else{
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(fuData.files[0]);
}
}
}
else {
alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
}
}}
MAX_SIZE is the maximum files size you allowed. You can find a good example in the following blog post which was written by me.
Upvotes: 4
Reputation: 1738
just follow this example http://jsbin.com/ulamor/213/edit?html,css,output
and submit your form when user input files with your desired file size range
Upvotes: 0
Reputation:
You can use this code with HTML 5 its tested Demo : Demo for this
<input type="file" id="file" />
var _URL = window.URL || window.webkitURL;
$("#file").change(function(e) {
var image, file;
if ((file = this.files[0])) {
image = new Image();
image.onload = function() {
alert("The image width is " +this.width + " and image height is " + this.height);
};
image.src = _URL.createObjectURL(file);
}
});
Upvotes: 8