Mahesh G
Mahesh G

Reputation: 1276

Implementing AngularJS file saver to download large text content

I wanted to implement filesaver where I wanted to download very large data of text . I saw there are some libraries already available such as

Angular JS File Saver

<div class="wrapper" ng-controller="ExampleCtrl as vm">
  <textarea
    ng-model="vm.val.text"
    name="textarea" rows="5" cols="20">
      Hey ho let's go!
  </textarea>
  <a href="" class="btn btn-dark btn-small" ng-click="vm.download(vm.val.text)">
    Download
  </a>
</div>

But I am not able to under stand , How I should implement in my AngularJS app. Below is the demo of My App

Here I am using data.json file to put the data in the UI. And I wanted to keep a download button where user clicks that buttong users should be able to download the content present in the data.json

Demo

Upvotes: 0

Views: 8588

Answers (1)

digit
digit

Reputation: 4565

You must first install FileSaver using package manager (i.e Bower) into the project and then you can use it in the application.

1) Install FileSaver using bower install FileSaver into Project

2) Define FileSaver module

3) Inject FileSaver in target controller

After successfully install the library, in your app.js please update your codes as below:

// Define module here
var app = angular.module('studentApp', ['FileSaver']);

// Inject FileSaver into target controller
app.controller('StudentCntrl', function($scope,$http, FileSaver) {     
   $scope.vm.download = function (data) {
      if (!data) {
        console.error('No data');
        return;
      }

      var newData = new Blob([data], { type: 'text/plain;charset=utf-8' });
       FileSaver.saveAs(newData, 'text.txt');
    };

    $http.get('data.json').then(function (response){
                  console.log(response.data.pages);
                $scope.data = response.data.PersonEvent.Body;
                $scope.vm.download($scope.data);
        });
});

Upvotes: 1

Related Questions