Rinktacular
Rinktacular

Reputation: 1136

FileReader() onload function not firing

I know this is a duplicate but none of the answers have helped so far..

I have this directive:

app.directive('fileReader', function () {
    return {
        scope: {
            fileReader: "="
        },
        link: function (scope, element) {
            $(element).on('change', function (changeEvent) {
                var files = changeEvent.target.files;
                if (files.length) {
                    var reader = new FileReader();
                    console.log('reader created');
                    reader.onload = function (e) {
                        console.log('onload hit');                           
                    };
                }
            });
        }
    };
}) 

And this DOM element linked to the directive:

<input type="file" id="file" file-reader="fileContent"/>  

When I select a file for my input, my console prints out reader created, but never prints onload hit. I can not figure out how to properly fire off my onload function. What am I doing wrong here?

Upvotes: 0

Views: 2868

Answers (1)

skdonthi
skdonthi

Reputation: 1442

### Directive ###
    app.directive('fileReader', ['$rootScope', function($rootScope) {
     return {
        scope: {
            fileReader:"="
        },
        link: function(scope, element) {
            $(element).on('change', function(changeEvent) {
                var files = changeEvent.target.files;
                if (files.length) {
                    $rootScope.uploadedFileName = files[0].name;
                    var r = new FileReader();
                    r.onload = function(e) {
                        var contents = e.target.result;
                        scope.$apply(function () {
                            scope.fileReader = contents;    
                            $rootScope.uploadedFileName = files[0].name;                        
                        });
                    };
                    r.readAsText(files[0]);
                }
            });
        }
     };
    }]);

### HTML ###

    <input type="file" accept=".csv" id="myFile" file-reader="fileContent"/>

Upvotes: 1

Related Questions