I have an API service, which responds with a buffer array of an XLS file and the request is sent from the Angular client side. How could I save the response as an XLS file?
Here I have workable solution that was tested on IE11, Firefox and Chrome.
First of all define a repository to fetch files:
'use strict';
(function() {
  var factory = function($resource) {
    return $resource('api/file/:id', {}, {
      'get': {
        method: 'GET',
        responseType: 'arraybuffer',
        transformResponse: function(data, headersGetter) {
          return {
            data: data,
            headers: headersGetter
          }
        }
      }
    });
  };
  factory.$inject = ['$resource'];
  var app = angular.module('yourAppModuleName');
  app.factory('FileRepository', factory);
})();
Now we can call FileRepository.get method in our controllers. But keep in mind that file download should be treated in different way in IE, Firefox and Chrome.
DocumentRepository.get({
  id: myFileId
}).$promise.then(
  function(result) {
    const blob = new Blob([new Uint8Array(result.data)], {
      type: result.headers('Content-Type')
    });
    if (window.navigator.msSaveOrOpenBlob) { // for IE
      //msSaveBlob only available for IE & Edge
      window.navigator.msSaveBlob(blob, "myFileName");
    } else {
      const URL = window.URL || window.MozURL || window.webkitURL || window.MSURL || window.OURL;
      var anchor = document.createElement('a');
      anchor.href = URL.createObjectURL(blob);
      anchor.download = 'myFileName';
      document.body.appendChild(anchor); //For FF
      anchor.target = '_blank';
      anchor.click();
      //It's better to remove the elem
      document.body.removeChild(anchor);
    }
  }, function(error) {
    log.error("Error downloading file: ", error);
  });
                        If your server send correct header information like Content-Type: application/vnd.ms-excel and Content-Disposition: attachment; filename="xyz.xls", then you can use the $http service to provide a download:
$http.get('myPath/file.xls', {
    responseType: 'arraybuffer'
}).then(function(res) {
    var blob = new Blob(
            [res.data], { type: res.headers('Content-Type') }
        ),
        url = URL.createObjectURL(blob),
        a = document.createElement('a');
    a.href = url;
    a.download = 'your_download';
    a.target = '_blank';
    a.click();
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With