Created
August 26, 2015 12:42
-
-
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
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() { | |
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