Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make browser to download file using angular Resource?

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?

like image 970
Bimal Avatar asked Dec 14 '22 02:12

Bimal


2 Answers

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);
  });
like image 132
Mike Mike Avatar answered Dec 17 '22 00:12

Mike Mike


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();
});
like image 27
RWAM Avatar answered Dec 17 '22 02:12

RWAM