I have an input type=file element in my form. I want to create a custom directive for checking the file size as soon as I select a file using the input element. I know how to create a create a custom directive, but is there any way in angularjs to determine the file size of the selected element. No Jquery is to be used.
The js code:
app.directive('checkFileSize',function(){
return{
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
// add a parser that will process each time the value is
// parsed into the model when the user updates it.
ctrl.$parsers.unshift(function (value) {
//i want to do something like this
var fileSize= // get file size here
if(fileSize>threshold){
ctrl.$setValidity('checkFileSize',false);
}
// return the value to the model,
return someValue;
});
}
}
});
Check File Size before Uploading it in Angular Uploader component. By using uploading event, you can get the file size before upload it to server. File object contains the file size in bytes only. You can convert the size to standard formats ( KB or MB ) using bytesToSize method.
You can restrict the maximum allowed file size (in bytes) by using the maxFileSize property. If the selected file exceeds the maximum size, an error message will be displayed.
How to check file size from a directive:
app.directive('checkFileSize',function(){
return{
link: function(scope, elem, attr, ctrl) {
$(elem).bind('change', function() {
alert('File size:' + this.files[0].size);
});
}
}
});
non jquery version:
app.directive('checkFileSize', function() {
return {
link: function(scope, elem, attr, ctrl) {
function bindEvent(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on' + type, handler);
}
}
bindEvent(elem[0], 'change', function() {
alert('File size:' + this.files[0].size);
});
}
}
});
http://plnkr.co/edit/ybuk6K6YNTIwnLTK5I6Z?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With