Last active
December 18, 2015 22:50
-
-
Save ocReaper/d1c9df3d62079024a35a to your computer and use it in GitHub Desktop.
Blob file download in Angular.js using $resource Full
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
<!doctype html> | |
<html lang="en" data-ng-app='app' data-ng-controller="EmailCtrl as email"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Example</title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.min.js"></script> | |
<script> | |
(function () { | |
'use strict'; | |
angular | |
.module('app') | |
.config(allowBlobLinkHrefs) | |
.controller('EmailCtrl', EmailCtrl) | |
.factory('Email', Email); | |
function Email($resource) { | |
var url = 'emails/', | |
EmailBase, xlsxContentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; | |
EmailBase = $resource(url + ':emailId', { | |
emailId: '@id' | |
}, { | |
getFile: { | |
method: 'GET', | |
url: url + ':emailId/files/:fileName', | |
params: { | |
emailId: '@id', | |
fileName: '@fileName' | |
}, | |
headers: { | |
accept: xlsxContentType | |
}, | |
responseType: 'arraybuffer', | |
cache: false, | |
transformResponse: function (data) { | |
return { | |
response: new Blob([data], { | |
type: xlsxContentType | |
}) | |
}; | |
} | |
} | |
}); | |
return EmailBase; | |
} | |
function EmailCtrl($scope, Email) { | |
var vm = this, | |
downloadableBlob = ''; | |
vm.getUploadedFileUrl = function getUploadedFileUrl() { | |
return downloadableBlob; | |
}; | |
$scope.$on('$stateChangeSuccess', updateDownloadableBlob); | |
function updateDownloadableBlob() { | |
.getFile({ | |
emailId: 1, | |
fileName: 'some.xlsx' | |
}) | |
.$promise | |
.then(function (data) { | |
downloadableBlob = URL.createObjectURL(data.response); | |
}); | |
} | |
} | |
function allowBlobLinkHrefs($compileProvider) { | |
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/); | |
} | |
}()); | |
</script> | |
</head> | |
<body> | |
<a target="_self" download="some.xlsx" ng-href="{{email.getUploadedFileUrl()}}"> | |
Download | |
</a> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment