Nicolai Schmid
Nicolai Schmid

Reputation: 1092

How to download a text file based on a generated String using AngularJS?

I'm trying to get AngularJS to trigger a file download when a user clicks on a button.

The file that should download has to contain data that is generated during the script execution, so the text file's content should be built from a basic string in AngularJS.

How do I implement this?

Here is some mockup code on how I imagine this would work:

var fileContent = 'foobar';
$scope.download = function() {
  filedownload.run(fileContent, 'filename.txt');
}

Upvotes: 2

Views: 5876

Answers (2)

Nicolai Schmid
Nicolai Schmid

Reputation: 1092

In order to achieve this you have to create an a tag in your HTML:

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

Controller:

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

And to enable the URL:

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

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

Upvotes: 4

stholzm
stholzm

Reputation: 3455

In simple cases, you can create a link with a Data URI:

var fileContent = 'foobar';
$scope.download = 'data:text/plain;base64,' + btoa(fileContent);

And then use it in your HTML template:

<a href="{{download}}">click here to download</a>

You may need to adapt the MIME type, depending on your string.

Upvotes: 2

Related Questions