ngResource blob download

by dvladir

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-resource.js"></script>
<body ng-app="app" ng-controller="MainController as main">
  <button ng-click="main.downloadFile()">
    Download
  </button>
</body>

JavaScript

function downloadBlob(fileName, blob){
	
  //IE case
  if (!!window.navigator.msSaveBlob){
  	window.navigator.msSaveBlob(blob, fileName);
    return;
  }
  
  //create blob and url
  var url = URL.createObjectURL(blob);

  //create invisible acnhor, to specify the file name
  var a = document.createElement('a');
  document.body.appendChild(a);
  a.style = "display: none";
  a.href = url;
  a.download = fileName;
  a.click();

  setTimeout(function(){
    URL.revokeObjectURL(url);
    document.body.removeChild(a);
  }, 100);

}


var app = angular.module('app', ['ng', 'ngResource']);

app.factory('UserFileSrv', ['$resource', function($resource){

  var userFile = {
      downloadFile: $resource('/img/logo.png', { //pass a valid url
        fileId: '@fileId'
      }, {
        download: {
          method: 'GET',
          isArray: false,
          responseType: 'blob',
          interceptor: {
            response: function(response) {
            	return {
              	headers: response.headers,
                data: response.data
              };
            }
          }
        }
      })
      };
    return userFile;

}]);

app.controller('MainController', ['UserFileSrv', function(UserFileSrv){

	this.downloadFile = function(){
  	UserFileSrv
    	.downloadFile.download({},
      function(response){
      		alert('success');
          
          //determine a file's name.
          //in fact it also could be retrived from headers
          var fileName = 'defaultName',
          		contentType = response.headers('Content-Type');
          if (contentType === 'image/png'){
          		fileName = 'img1.png';
          }    
          
          downloadBlob(fileName, response.data);
      }, function(response){
      		alert('error');
          console.log(response);
      })
  }

}]);