0

I just followed the way mentioned in this article to upload a file https://www.tutorialspoint.com/angularjs/angularjs_upload_file.htm link:

function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                console.log("len:"+element[0].files);
               modelSetter(scope, element[0].files);
                console.log("filenames:"+element[0].files);
            });
        });                                                                                  

Here when I debug the element does not contain any attributes called files, so I always getting it as undefined. I have tried many different ways, all resulted with the same issue. How to solve this issue? Why element doesn't have files attributes?

Avag Sargsyan
  • 2,437
  • 3
  • 28
  • 41

2 Answers2

0

My File upload directive code

  module.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(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

And usage code

<input class="import-export-hide-fileinput" type="file" id="file" file-model="ctrl.fileToImport" name="file"
                   accept="undefined">

Serivce calling

mySerice.importReports(self.fileToImport)
                        .then(self.onImportSuccess, self.onError);

Service code

importReports: function (fileInput) {
            var fd = new FormData();
            fd.append('file', fileInput);
            return $http.post('/path/import', fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            });
        },
rijin
  • 1,709
  • 12
  • 21
0

In HTML:

<input type="file" id="file" name="file"/>
<button ng-click="upload()">Upload</button>

In controller:

$scope.upload= function() {
    var f = document.getElementById('file').files[0],
        r = new FileReader();

    r.onloadend = function(e) {
      var data = e.target.result;
      //send your binary data via $http or $resource or do anything else with it
    }

    r.readAsBinaryString(f);
}

Hope It helps..!