您的位置:首页 > Web前端 > JavaScript

Blob file download in Angular.js using $resource

2016-07-12 22:24 375 查看
<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
rawgistfile1.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
rawgistfile2.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
rawgistfile3.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
rawgistfile4.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
rawgistfile5.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
rawgistfilefull.html hosted with 

 by GitHub
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: