Categories
Uncategorized

Download Files using only AngularJS 1.X

We create a new Blob object using dummy data and then use it as an object URL in an anchor tag which is created dynamically. We don’t need to attach this element to the DOM (Document Object Model), so we simply trigger a click event on it, to begin downloading. The dummy data used here is a String Array. This code was tested using Chrome and AngularJS 1.6.
Note: For this to work, blob must be added to your whitelist configuration in the angular app.

angular.module('app', [])
.config(['$compileProvider',
function($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
}
])

Here is the complete example 1,

angular.module('app', [])

.config(['$compileProvider',
 function($compileProvider) {
 $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
 }
])

.controller('appController', function($scope, $window) {

 var data = [
 "This is a log number 1.",
 "This is a log number 2.",
 "This is a log number 3.",
 "This is a log number 4."
 ];

 var blob = new Blob([data.join('\r\n')], {
 type: 'text/plain'
 });

 var downloadLink = angular.element('<a></a>');

 var url = $window.URL || $window.webkitURL;

 downloadLink.attr('href', url.createObjectURL(blob));

 downloadLink.attr('download', 'logs_file_name');

 downloadLink[0].click();
});

Demo

We can also output Javascript Objects in the form of JSON data.

angular.module('app', [])

.config(['$compileProvider',
  function($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
  }
])

.controller('appController', function($scope, $window) {

  var jsObj = {
    name: "Shiva",
    country: "US"
  };

  var blob = new Blob([angular.toJson(jsObj)], {
    type: 'text/json;charset=utf-8'
  });

  var downloadLink = angular.element('');

  var url = $window.URL || $window.webkitURL;

  downloadLink.attr('href', url.createObjectURL(blob));

  downloadLink.attr('download', 'logs_file_name.json');

  downloadLink[0].click();
});

Demo