Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you serve a file for download with AngularJS or Javascript?

I have some text in a hidden textarea. When a button is clicked I would like to have the text offered for download as a .txt file. Is this possible using AngularJS or Javascript?

like image 247
nickponline Avatar asked May 13 '13 03:05

nickponline


People also ask

How do I download a script in AngularJS?

To download AngularJS library, go to angularjs.org -> click download button, which will open the following popup. Select the required version from the popup and click on download button in the popup.

How do you create a download link in JavaScript?

Creating the download linkCreate an object URL for the blob object. Create an anchor element ( <a></a> ) Set the href attribute of the anchor element to the created object URL. Set the download attribute to the filename of the file to be downloaded.


2 Answers

You can do something like this using Blob.

<a download="content.txt" ng-href="{{ url }}">download</a> 

in your controller:

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

in order to enable the URL:

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

Please note that

Each time you call createObjectURL(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them. Browsers will release these automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.

Source: MDN

like image 89
Tosh Avatar answered Oct 21 '22 05:10

Tosh


Just click the button to download using following code.

in html

<a class="btn" ng-click="saveJSON()" ng-href="{{ url }}">Export to JSON</a>

In controller

$scope.saveJSON = function () {  			$scope.toJSON = '';  			$scope.toJSON = angular.toJson($scope.data);  			var blob = new Blob([$scope.toJSON], { type:"application/json;charset=utf-8;" });			  			var downloadLink = angular.element('<a></a>');                          downloadLink.attr('href',window.URL.createObjectURL(blob));                          downloadLink.attr('download', 'fileName.json');  			downloadLink[0].click();  		};
like image 38
Amrut Avatar answered Oct 21 '22 06:10

Amrut