FileSaver.js is a library that makes it easy to save files on the client-side. To use FileSaver.js in your AngularJS application, follow the steps below:
- Install and include FileSaver.js:
Include the FileSaver.js library in your project. You can either download it from the official GitHub repository (https://github.com/eligrey/FileSaver.js/) or use a CDN like the following:
HTML Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
- Create an AngularJS module and controller:
Create a new AngularJS module and controller for your application:
JS Code
angular.module('app', [])
.controller('MainController', function($scope) {
// Your controller logic here
});
- Create a function to save a file:
In your controller, create a function that uses the saveAs
method from FileSaver.js to save a file:
JS Code
$scope.saveFile = function() {
var data = "Hello, World!";
var blob = new Blob([data], { type: "text/plain;charset=utf-8" });
saveAs(blob, "example.txt");
};
In this example, we create a new Blob object with some sample text data and save it as “example.txt”. You can replace the data with your own content and adjust the MIME type and file name as needed.
- Add a button to save the file:
Add a button to your HTML that calls the saveFile()
function:
HTML Code
<body ng-controller="MainController">
<button ng-click="saveFile()">Save File</button>
</body>
Here’s the complete example:
index.html
– Main HTML file:
HTML Code
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainController">
<button ng-click="saveFile()">Save File</button>
</body>
</html>
app.js
– Main JavaScript file:
JS Code
angular.module('app', [])
.controller('MainController', function($scope) {
$scope.saveFile = function() {
var data = "Hello, World!";
var blob = new Blob([data], { type: "text/plain;charset=utf-8" });
saveAs(blob, "example.txt");
};
});
When you click the “Save File” button, it will trigger the saveFile()
function and save the sample text data as “example.txt” using the FileSaver.js library.