Created
December 1, 2017 12:35
-
-
Save L2jLiga/1af1a93a3caef7bbd7b88beab2d3f198 to your computer and use it in GitHub Desktop.
AngularJS 1.6.x FileReader directive for async file uploading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
'use strict'; | |
var utils = angular.module('utils'); | |
utils.directive('fileReader', function (EVENTS) { | |
return { | |
restrict: 'A', | |
scope: { | |
fileReader: '=' | |
}, | |
link: function (scope, element) { | |
element.bind('change', function (changeEvent) { | |
var reader = new FileReader(); | |
reader.onload = function (loadEvent) { | |
scope.$apply(function () { | |
scope.fileReader = dataURItoBlob(loadEvent.target.result); | |
}); | |
}; | |
reader.readAsArrayBuffer(changeEvent.target.files[0]); | |
}); | |
/** | |
* Convert arrayBuffer to raw binary data held in a string | |
* @param {ArrayBuffer} fileArrayBuffer - Array buffer which contains file | |
* @return {Blob} converted file to blob | |
*/ | |
function dataURItoBlob(fileArrayBuffer) { | |
var bytesArray = new Uint8Array(fileArrayBuffer); | |
return new Blob([bytesArray]); | |
} | |
scope.$on(EVENTS.FILE_READER.RESET, function () { | |
element.val(''); | |
scope.fileReader = null; | |
}); | |
} | |
}; | |
}); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
'use strict'; | |
describe('Test suite for file-reader directive', function () { | |
beforeEach(function () { | |
angular.mock.module('utils'); | |
}); | |
var $rootScope, | |
$compile, | |
$scope, | |
element; | |
beforeEach(inject(function (_$rootScope_, | |
_$compile_) { | |
$rootScope = _$rootScope_; | |
$scope = $rootScope.$new(); | |
$compile = _$compile_; | |
})); | |
beforeEach(function () { | |
var html = '<input data-file-reader="someElement"></input>'; | |
element = $compile(angular.element(html))($scope); | |
$rootScope.$digest(); | |
}); | |
it('should be correctly compiled', function () { | |
expect(element).toBeTruthy(); | |
}); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment