Skip to content

Instantly share code, notes, and snippets.

@hasghari
Last active Dec 25, 2015
Embed
What would you like to do?
angular file upload preview module
(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