Search code examples
javascriptangularjsng-file-upload

Can not get files orderly in an array using Angular.js


I have one issue while uploading the multiple files using ng-file-upload in Angular.js. I am explaining my code below first.

<input type="file" class="filestyle form-control" data-size="lg" name="bannerimage" id="bannerimage"  ng-model="file" ngf-pattern="'image/*'" accept="image/*" ngf-max-size="2MB" ngf-min-height="100" ngf-resize="{width: 100, height: 100}"  custom-on-change="uploadFile" required="required" ngf-select="onFileSelect($file);"  ngf-multiple="true">
</div>
<label for="bannerimage" accesskey="B" ><span class="required">*</span> View Image</labe
<div style="padding-bottom:10px;" ng-repeat="pht in stepsModel">
<img ng-src="{{pht.image}}" border="0" name="bannerimage" style="width:70px; height:70px;" id="imgId">
</div>

My controller side code is given below.

$scope.stepsModel = [];
    $scope.allFiles=[];
    $scope.uploadFile = function(event){
        console.log('event',event.target.files);
        var files = event.target.files;
        for (var i = 0; i < files.length; i++) {
         var file = files[i];
             var reader = new FileReader();
             reader.onload = $scope.imageIsLoaded; 
             reader.readAsDataURL(file);
     }
    };
    $scope.imageIsLoaded = function(e){
    $scope.$apply(function() {
        var data={'image':e.target.result};
        $scope.stepsModel.push(data)
    });
}
$scope.submitImage=function(){
    console.log('all files',$scope.allFiles);
}
$scope.onFileSelect = function($files) {
         $scope.allFiles.push($files);

}

Here my problem is when i am checking the no of images url in the console message present inside submitImage function its coming like below.

all files [Blob, null, Blob, null, Blob]
0: Blob

1: null   
2: Blob  
3: null    
4: Blob 

Objectlength: 5v

Here i have uploaded only 3 files but length is showing 5 means its not serially coming suppose for 0th index one file is there then next file is occupying 2nd index.Here i need all files should come serially.Please help me.


Solution

  • I think first you need to check why null elements are there in the array. Put a log in onFileSelect function and check allFiles array after each file selected.