Skip to content

Instantly share code, notes, and snippets.

@irfanfadilah
Created January 23, 2017 04:58
Show Gist options
  • Select an option

  • Save irfanfadilah/6d3890f268005ca8a9fc01b8dc46f5e7 to your computer and use it in GitHub Desktop.

Select an option

Save irfanfadilah/6d3890f268005ca8a9fc01b8dc46f5e7 to your computer and use it in GitHub Desktop.
Simple Validation and Preview for Image Upload (JavaScript)
var _URL = window.URL || window.webkitURL;
$("#article_image").change(function(){
var file, img, reader;
if ((file = this.files[0])) {
img = new Image();
img.onload = function(){
if ( (this.width < 960) || (this.height < 300) ) {
alert("Image must be larger than 960x300 pixels!")
} else {
reader = new FileReader();
reader.onload = function (e) {
$('#image-preview').attr('src', e.target.result);
}
reader.readAsDataURL(file);
}
}
img.src = _URL.createObjectURL(file);
}
});
@irfanfadilah
Copy link
Author

What this codes do? It's listen to file input (#article_image) on event changes.

If the image size is valid, the image will be shown/displayed on image tag (#image-preview), else it will showing alert message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment