prince
prince

Reputation: 611

How can I limit the size of attachment (file upload) in AngularJS?

I want the best way to upload files with loading image in AngularJS. At the same time i want to limit the size to 10MB.

Please give the best way to achieve this?

Upvotes: 15

Views: 59233

Answers (5)

Imran Kabir
Imran Kabir

Reputation: 9

Use directive

ngApp.directive('fileModel', ['$parse', function ($parse) {

return {

restrict: 'A',

link: function (scope, element, attrs) {

var model = $parse(attrs.fileModel);

var modelSetter = model.assign;

 element.bind('change', function () {

var fileSize = this.files[0].size / 1024;

if (fileSize > 600) {

alert("File size is larze; maximum file size 600 KB");

} else {

scope.$apply(function () {

 modelSetter(scope, element[0].files[0]);

 });                
}          
 });    
 }   
};
}]);

Upvotes: 1

CountZero
CountZero

Reputation: 6389

This is the directive I use to both pull the file into Angulars scope, validate the file size and validate extensions.

var fileUpload = () => {

    return {
        scope: {
            file: '='
        },
        require: 'ngModel',
        link(scope, el, attrs, ctrl) {

            el.bind('change', (event) => {
                var file = event.target.files[0];
                var extn = file.name.split(".").pop().toLowerCase();

                if (attrs.validExtensions != null) {
                    const extensions = attrs.validExtensions.split(',');
                    var validExtension = false;

                    extensions.forEach((x) => {
                        if (x === extn) {
                            validExtension = true;
                        }
                    });

                    ctrl.$setValidity('type', validExtension);
                }

                if (attrs.maxSize != null) {
                    var maxSize = attrs.maxSize;

                    var valid = (file.size / 1024) <= maxSize;
                    ctrl.$setValidity('size', valid);
                } else {
                    console.log('max size ScriptNotifyEvent set');
                }

                scope.file = file ? file : undefined;
                scope.$apply();
            });
        }
    };
};

HTML

<input type="file" file="File1" id="File1" name="File1" ng-model="File1" valid-extensions="doc,docx,xls,xlsx,pdf,tiff,zip,ppt,pptx" max-size="20000" />

<div class="alert alert-danger" ng-show="form.File1.$error.type && (form.File1.$touched || Submitted)" Role="alert">This form only allows the following file types: *.doc, *.docx, *.xls, *.xlsx, *.ppt, *.pptx, *.pdf, *.tiff, *.zip</div>

<div class="alert alert-danger" ng-show="form.File1.$error.size && (form.File1.$touched || Submitted)" Role="alert">The file is too large to send to us, please limit indivudual files to 20 megabytes.</div>

Upvotes: 0

Jack
Jack

Reputation: 734

You can use this lib:

https://github.com/danialfarid/ng-file-upload

  ngf-min-size='10' // minimum acceptable file size in bytes
  ngf-max-size='1000' // maximum acceptable file size in bytes

Upvotes: 5

runderworld
runderworld

Reputation: 131

While this question is somewhat old, I still think it's worthwhile to provide the best possible answer for those seeking it. The answer above relies on jQuery for the superficial aspects, but let's use a style fitting for Angular development.

Here I reference the actual library author's own recommendation when asked the same question, altering it for the size asked in the question above:

uploader = new FileUploader();
//...
uploader.filters.push({
    'name': 'enforceMaxFileSize',
    'fn': function (item) {
        return item.size <= 10485760; // 10 MiB to bytes
    }
});

EXAMPLE UPDATED ABOVE: to reflect changes to the angular-file-upload API.

Note that this relies on the file's size attribute (Blob size in bytes), which is supported only by modern browsers (namely IE10 and up).

Upvotes: 10

Murugan Pandian
Murugan Pandian

Reputation: 778

See this example you get some idea

HTML CODE :

  <form  class="upload-form">
        <input class="upload-file" data-max-size="2048" type="file" >
        <input type=submit>
    </form>

SCRIPT:

$(function(){
    var fileInput = $('.upload-file');
    var maxSize = fileInput.data('max-size');
    $('.upload-form').submit(function(e){
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                alert('file size is more than ' + maxSize + ' bytes');
                return false;
            }else{
                alert('file size is correct - '+fileSize+' bytes');
            }
        }else{
            alert('Please select the file to upload');
            return false;
        }

    });
});

its already in jsfiddle

Upvotes: 4

Related Questions