Skip to content

Instantly share code, notes, and snippets.

@thim81
Forked from mir4ef/save-blob-ctrl.js
Created June 13, 2019 14:38
Show Gist options
  • Save thim81/94ed8753378bb6b23b9dc50a6980a7a7 to your computer and use it in GitHub Desktop.
Save thim81/94ed8753378bb6b23b9dc50a6980a7a7 to your computer and use it in GitHub Desktop.
Save a blob file in AngularJS 1.x
function SaveFileCtrl (SaveFileService) {
var vm = this;
function downloadFile(someArgument) {
SaveFileService.downloadFile({
param: someArgument
}, function (response) {
var fileName = response.headers['content-disposition'].split("=")[1].replace(/\"/gi,'');
var fileType = response.headers['content-type'] + ';charset=utf-8';
var blob = new Blob([response.data], { type: fileType });
var objectUrl = window.URL || window.webkitURL;
var link = angular.element('<a/>');
link.css({ display: 'none' });
link.attr({
href : objectUrl.createObjectURL(blob),
target: '_blank',
download : fileName
})
link[0].click();
// clean up
link.remove();
objectUrl.revokeObjectURL(blob);
}, function (error) {
console.error(error);
});
}
vm.downloadFile = downloadFile;
}
function SaveFileService($resource) {
return $resource('api/route/:param', { param: '@param' }, {
downloadFile: {
method: 'get',
responseType: 'arraybuffer',
transformResponse: function(data, headers) {
var response = {};
response.data = data;
response.headers = headers();
return response;
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment