Blob file download in Angular.js using $resource

<div ng-controller="appController" ng-app="app">
    <a ng-href="{{ fileUrl }}" download="file.txt">download</a>

</div>


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


app.config(['$compileProvider', function ($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
}]);


app.controller('appController', function ($scope, $window) {
    var data = 'some data here...',
        blob = new Blob([data], { type: 'text/plain' }),
        url = $window.URL || $window.webkitURL;
    $scope.fileUrl = url.createObjectURL(blob);
});


========================================================================================================



In this tutorial we will create a simple Angular application which can create a link of a downloadable file through $resource!

So first of all we will use XHR2 in order to use ArrayBuffer a new response type. Then we’ll use the HTML5 download attribute to name our blob file.

Let’s create our example resource called Email. Then add our custom action called getFile, in order to download the attached xlsx files.

  (function () {
  'use strict';
   
  angular
  .module('app')
  .factory('Email', Email);
   
  function Email($resource) {
  var url = 'emails/'
  , EmailBase;
   
  EmailBase = $resource(url + ':emailId', {emailId: '@id'}, {
  getFile: {
  method: 'GET',
  url: url + ':emailId/files/:fileName',
  params: {
  emailId: '@id',
  fileName: '@fileName'
  },
  cache: false
  }
  });
   
  return EmailBase;
  }
  }());
view raw gistfile1.js hosted with  ❤ by  GitHub

Now extend it to be able to store the file in the memory. Here we have to set the sever’s responseType to ArrayBuffer. Here’s a catch: Angular can’t handle it so we have to transform the response.
All what we will do is turn the data into blob with the correct mime type.

  /* global Blob */
   
  (function () {
  'use strict';
   
  angular
  .module('app')
  .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;
  }
  }());
view raw gistfile2.js hosted with  ❤ by  GitHub

Let’s create our controller method. Here we create an url for the blob we got from our API.

  /* global URL */
   
  (function () {
  'use strict';
   
  angular
  .module('app')
  .controller('EmailCtrl', EmailCtrl);
   
  function EmailCtrl($scope, Email) {
  var vm = this
  , downloadableBlob = '';
   
  vm.getUploadedFileUrl = function getUploadedFileUrl() {
  return downloadableBlob;
  };
   
  $scope.$on('$stateChangeSuccess', updateDownloadableBlob);
   
  function updateDownloadableBlob() {
  Email
  .getFile({
  emailId: 1,
  fileName: 'some.xlsx'
  })
  .$promise
  .then(function (data) {
  downloadableBlob = URL.createObjectURL(data.response);
  });
  }
  }
  }());
view raw gistfile3.js hosted with  ❤ by  GitHub

Model: done, ViewModel: done, view is the next. Here we’ll use another new feature in HTML5: the download attribute, which is used to force downloading instead of opening the file and be able to customise the name of the file. In our case it’s extremely important, due to the blob file name is made up by a few random character. Also note target self, which is a little fix for some “browser’s”…

  <a target="_self" download="some.xlsx" ng-href="{{email.getUploadedFileUrl()}}">
  Download
  </a>
view raw gistfile4.tpl.html hosted with  ❤ by  GitHub

At this point we could think: Yay! We made it! But it’s just not true. Angular adds an unsafe prefix to our URL due to security reasons against blob. So at the final step we have to disable this in a config method, by adding blob to the RegEx whitelist.

  (function () {
  'use strict';
   
  angular
  .module('app')
  .config(allowBlobLinkHrefs);
   
  function allowBlobLinkHrefs($compileProvider) {
  $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
  }
  }());
view raw gistfile5.js hosted with  ❤ by  GitHub

Thanks for reading! You can check out the final code below in a gist example with inlined angular code.

  <!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() {
  Email
  .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>
view raw gistfilefull.html hosted with  ❤ by  GitHub


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值