Skip to content

Instantly share code, notes, and snippets.

@kalpesh-fulpagare
Last active August 29, 2015 14:11
Show Gist options
  • Save kalpesh-fulpagare/10210bfe1e1d89819532 to your computer and use it in GitHub Desktop.
Save kalpesh-fulpagare/10210bfe1e1d89819532 to your computer and use it in GitHub Desktop.
Angular Directive to Show File Upload image thumbnail
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