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?

2
  • I am working with angularjs project. Commented Jun 13, 2017 at 10:47
  • 1
    StackOverflow is littered with examples of angularjs BLOB downloads. Just don't limit yourself to the .jpg format. Just change MIME types of other solutions, that is all. Commented Jun 13, 2017 at 10:56

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.