We have many ways to download files in angular JS. If the file data comes from the rest api then the way to download files is different. If we have a complete file path like http://demo.com/download/sample.pdf then by using anchor tag or into the controller using window.open() we can download the files. Below are the examples for downloading files.

1. Download file using anchor tag & url

HTML

download

JS Controller

var content = 'file content for example'; 
var blob = new Blob([ content ], { type : 'text/plain' }); 
$scope.url = (window.URL || window.webkitURL).createObjectURL( blob );

We have to enable blob or outside urls to support downloading files. To add this support the below code is used to white list urls to get the access.

JS Controller (App Controller)

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

app.config([‘$compileProvider’, function ($compileProvider) { … }]);
This is an AngularJS configuration block that allows you to configure various aspects of your application during the config phase.

$compileProvider.aHrefSanitizationWhitelist is used to provide url sanitization whitelist in angularjs.

2. Download file using Rest API

HTML


HTML

define([], function () {
 var controller = function ($scope, $http) {
   $scope.downloadFile = function () {
     const url = "https://sample.com/files/sample.pdf";
     var filename = "sample.pdf";
     $http
       .get(url, { responseType: "arraybuffer" })
       .then(function (response) {
         var blob = new Blob([response.data], { type: "application/pdf" });
         var url = URL.createObjectURL(blob);
         var a = document.createElement("a");
         a.href = url;
         a.download = filename;
         a.click();
         URL.revokeObjectURL(url);
       });
   };
 };
 controller.$inject = ["$scope", "$http"];
 return controller;
});

In angular js the $http is the service to communicate with the remote http server using xml http request. This function has multiple methods like get, post, put, patch, delete and option with promises. Using a ‘promise’ else ‘then’ statement we can get the response. The above example uses the GET http method to download files.
Make sure we have to inject $http in the controller to use the $http service.

3. Download file using Rest API With Progress Bar Or Percentage

HTML


Please wait for the file to be downloaded.

Download progress : {{downloadProgress}}%

JS Controller

define([], function () {
 var controller = function ($scope, $http, $timeout) {
   $scope.downloadProgress = 0;
   $scope.downloadFile = function () {
     const url =
       "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
     var filename = "sample.mp4";
     $http
       .get(url, {
         responseType: "arraybuffer",
         eventHandlers: {
           progress: function (progressEvent) {
             $timeout(function () {
               if (progressEvent.lengthComputable) {
                 $scope.downloadProgress = Math.round(
                   (progressEvent.loaded / progressEvent.total) * 100
                 );
               }
             });
           },
         },
       })
       .then(function (response) {
         var blob = new Blob([response.data], { type: "application/octate" });
         var url = URL.createObjectURL(blob);
         var a = document.createElement("a");
         a.href = url;
         a.download = filename;
         a.click();
         URL.revokeObjectURL(url);
         $timeout(function () {
           $scope.downloadProgress = 0;
         });
       });
   };
 };
 controller.$inject = ["$scope", "$http", "$timeout"];
 return controller;
});

Using the eventHandlers object in $http we can achieve the progress of file downloading.
Above example sets the progress event and shows download progress in percentage.
$timeout is the service to force your callback function to always run the asynchronous call.
without $timeout service we can not bind or update value in $scope. Thus we have to use this solution to show the updated value in $scope. This helps to call the code a single $apply block.
Make sure we have to inject a $http & $timeout in the controller to use the $http & $timeout services.

Support On Demand!

                                         
Angular