Skip to content

Instantly share code, notes, and snippets.

@matthewbednarski
Created August 26, 2015 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewbednarski/149a351f0446b484800b to your computer and use it in GitHub Desktop.
Save matthewbednarski/149a351f0446b484800b to your computer and use it in GitHub Desktop.
An example implementation for downloading and viewing a pdf in an AngularJS app
(function() {
var app = angular
.module('app',[])
.controller('MyController', ['$q', '$sce', 'myService', Controller])
.service('myService', ['$q', '$http', Service]);
function Controller($scope, $q, $sce, service) {
var ctl = this;
this.download = function(doc) {
service.downloadDoc(doc, ctl.x_auth)
.then(function(result) {
ctl.pdf.src = $sce.trustAsResourceUrl(result);
})
.catch(function(result) {
console.error(result);
});
};
}
function Service($q, $http) {
var svc = {
url_prefix: '/xdsconsumer/api'
};
// http://stackoverflow.com/questions/21628378/angularjs-display-blob-pdf-in-an-angular-app
svc.downloadDoc = function(doc_path, auth_params) {
var defer = $q.defer();
var url = svc.url_prefix + doc_path
$http({
method: 'GET',
url: url,
responseType: 'arraybuffer',
headers: {
'x-auth': auth_params
}
})
.success(function(results) {
if (results !== undefined) {
var file = new Blob([results], {
type: 'application/pdf'
});
var fileURL = URL.createObjectURL(file);
defer.resolve(fileURL);
} else {
defer.reject(new Error("No motive!"));
}
})
.error(function(results) {
defer.reject(new Error(results));
});
return defer.promise;
};
return svc;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment