1

I am working on angularjs javascript project, in this I need to download the file.

I have my files uploaded to server and I have the path to access them, now I need to download them as we see in downloading file in browser, to achieve this I need to create blob object with physical file path.

Like my path is http://localhost:8080/app/ns.jpg, so I can give app/ns.jpg and I want its blob object.

File type can be any type. How can I create blob to download the file from a known path?

Neelam Sharma
  • 2,745
  • 4
  • 32
  • 73

1 Answers1

1

You can use $http service with setting responseType to arraybuffer/blob.

It doesn't differ a lot from the native javascript solution.

angular.module('myApp', [])
.controller('MyCtrl', ['$scope', '$http', '$window', function MyCtrl($scope, $http, $window) {
  var ctrl = this;
  
  ctrl.download = download;
  
  var imgUrl = 
  '//cors-anywhere.herokuapp.com/http://www.wallpapersxl.com/get/2339478';
  
  function download () {
    $http.get(imgUrl, { responseType: 'arraybuffer' }).then(function (response) {
      ctrl.file = new Blob([response.data], {type: 'image/jpeg'});
      ctrl.url = getUrl(ctrl.file);
    });
  }
  
  function getUrl (blob){
    var url = $window.URL || $window.webkitURL;
    return url.createObjectURL(blob);
  }
  
  $scope.$ctrl = ctrl;
}]);
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">  
    <button ng-click="$ctrl.download()" class="testBtn">
      Download
    </button>


    <div ng-if="$ctrl.file">
      <span>{{$ctrl.file.size}} -- {{$ctrl.file.type}}</span>
      <img ng-src="{{$ctrl.url}}" />
    </div>
  </div>
</div>
Stanislav Kvitash
  • 4,614
  • 18
  • 29