Last active
December 25, 2015 21:58
-
-
Save hasghari/7045943 to your computer and use it in GitHub Desktop.
angular file upload preview module
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 (module) { | |
"use strict"; | |
var fileReader = function ($q) { | |
var onLoad | |
, onError | |
, onProgress | |
, getReader | |
, readAsDataURL | |
; | |
onLoad = function (reader, deferred, scope) { | |
return function () { | |
scope.$apply(function () { | |
deferred.resolve(reader.result); | |
}); | |
}; | |
}; | |
onError = function (reader, deferred, scope) { | |
return function () { | |
scope.$apply(function () { | |
deferred.reject(reader.result); | |
}); | |
}; | |
}; | |
onProgress = function (reader, scope) { | |
return function (event) { | |
scope.$broadcast("fileProgress", | |
{ | |
total: event.total, | |
loaded: event.loaded | |
}); | |
}; | |
}; | |
getReader = function (deferred, scope) { | |
var reader = new FileReader(); | |
reader.onload = onLoad(reader, deferred, scope); | |
reader.onerror = onError(reader, deferred, scope); | |
reader.onprogress = onProgress(reader, scope); | |
return reader; | |
}; | |
readAsDataURL = function (file, scope) { | |
var deferred = $q.defer() | |
, reader = getReader(deferred, scope) | |
; | |
reader.readAsDataURL(file); | |
return deferred.promise; | |
}; | |
return { | |
readAsDataUrl: readAsDataURL | |
}; | |
}; | |
module.factory("fileReader", ["$q", fileReader]); | |
}(window.angular.module("app"))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment