Last active
August 29, 2015 14:11
-
-
Save kalpesh-fulpagare/10210bfe1e1d89819532 to your computer and use it in GitHub Desktop.
Angular Directive to Show File Upload image thumbnail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('image-preview-demo',[]).directive('imgPreviewElem', [function () { | |
return { | |
restrict: 'AE', | |
link: function(scope, elem, attrs) { | |
console.log("directive called") | |
elem.bind('change', function () { | |
var file=elem[0].files[0], | |
imageType=/(image.jpeg|image.png|image.jpg)/, | |
imgElementId = attrs.imgPreviewElem; | |
//Image match expression | |
if(file.type.match(imageType)){ | |
var oldImg=document.getElementById(imgElementId), img=document.createElement("img"), thumbDiv = oldImg.parentNode; | |
img.file = file; | |
img.id = imgElementId; | |
thumbDiv.replaceChild(img, oldImg); | |
reader = new FileReader(); | |
reader.onload = (function(aImg) { | |
return function(e) { | |
aImg.src = e.target.result; | |
}; | |
})(img); | |
reader.readAsDataURL(file); | |
} | |
else | |
alert("Unsupported File\nOnly image files(jpeg, jpg, png) are allowed to upload!"); | |
}); | |
} | |
}; | |
}]); | |
/* HTML CODE | |
* <input type='file' img-preview-elem="ui-preview-element"> | |
* <div> | |
* <img id='ui-preview-element' /> | |
* </div> | |
**********/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment