Skip to content

Instantly share code, notes, and snippets.

@odytrice
Created October 15, 2015 19:55
Show Gist options
  • Save odytrice/b0a5828783ae00e2284c to your computer and use it in GitHub Desktop.
Save odytrice/b0a5828783ae00e2284c to your computer and use it in GitHub Desktop.
/// <reference path="notification.ts" />
/// <reference path="../app.ts" />
module App.Services {
export class FileService {
static $inject = ["_notify", "$rootScope", "$q"];
scope: ng.IRootScopeService;
notify: NotifyService;
Q: ng.IQService;
constructor(_notify: NotifyService, $rootScope: ng.IRootScopeService, $q: ng.IQService) {
this.notify = _notify;
this.scope = $rootScope;
this.Q = $q;
}
upload<T>(url: string, name: string, file: File) {
//Create new Deferred Object
var defer = this.Q.defer<T>();
var scope = this.scope;
var notify = this.notify;
//Show Loading
var $loader = angular.element("[data-loader]").show(10);
var fd = new FormData();
fd.append(name, file);
var xhr = new XMLHttpRequest();
//Attach Event Handlers
xhr.upload.onprogress = function (e) {
scope.$apply(function () {
if (e.lengthComputable) {
defer.notify(e);
}
});
};
xhr.onload = function (e) {
scope.$apply(function () {
if (xhr.status == 200) {
var operation = <Operation<T>> JSON.parse(xhr.responseText);
if (operation.Succeeded) {
defer.resolve(operation.Result);
} else {
notify.error(operation.Message, "Server Error");
defer.reject(operation.Message);
}
}
else {
var message = "An Error Occured during Server Processing: " + xhr.responseText;
notify.error(message, "Server Error");
defer.reject(message);
}
$loader.hide(20);
});
};
xhr.onerror = function (e: ErrorEvent) {
scope.$apply(function () {
notify.error(e.message);
defer.reject(e.message);
$loader.hide(20);
});
};
xhr.onabort = function (e) {
scope.$apply(function () {
var message = "Upload Aborted";
notify.error(message);
defer.reject(message);
$loader.hide(20);
});
};
//Peform Actual Upload
xhr.open("POST", url, true);
xhr.send(fd);
return defer.promise;
}
}
App.module.service("_file", FileService);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment