98

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?

Vandervals
  • 4,724
  • 5
  • 33
  • 81
nickponline
  • 22,615
  • 27
  • 86
  • 138
  • 1
    What browsers do you support? This can be solved in some creative ways (like data-uris, blobs, the browser's history API, etc) but that really depends. – Benjamin Gruenbaum May 13 '13 at 18:07
  • [Angular File Saver](https://github.com/alferov/angular-file-saver) is a good polyfill for less modern browsers. – georgeawg Mar 12 '17 at 23:19

11 Answers11

112

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

ozba
  • 6,176
  • 4
  • 30
  • 39
Tosh
  • 35,589
  • 11
  • 64
  • 54
  • 3
    Modern browsers & IE10+ – dave1010 Dec 11 '13 at 17:10
  • @thriqon wow firefox + chrome really showing the others up there! – JonnyRaa Jul 14 '14 at 16:08
  • Great solution, but `$scope.url` didn't worked for me. I had to use `window.location` instead. – Gustavo Straube Oct 20 '14 at 15:43
  • 7
    I noticed that then anchor tag is prefixed with unsafe. In order to get around that you will need to add 'blob' to the white list in your app.js, using $compileProvider ` .config(['$compileProvider', function ($compileProvider) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/); } ` https://docs.angularjs.org/api/ng/provider/$compileProvider – coderman Dec 26 '14 at 06:16
  • The whitelist above is correct, but be careful if attempting to copy-and-paste; there are special bytes in the middle of "blob" (looks like a square on my screen), which prevents it from working properly. I tried to repeat without the special bytes, but stackoverflow appears to add them back. – ash Apr 24 '15 at 18:21
  • How does this behaves with large files? ... will overload the browser? – Rafael Jun 30 '15 at 09:21
  • 10
    The `download` attribute isn't supported in any IE or Safari versions though http://caniuse.com/#feat=download – Aaron Jul 09 '15 at 17:11
  • This open file in a new window instead of showing save file dialog. – fdrv Apr 06 '16 at 05:21
33

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();
  };
Amrut
  • 387
  • 1
  • 5
  • 5
  • 1
    @Amrut worked for me as needed, but can you explain the code ? – Harsh Daftary Jul 29 '15 at 08:29
  • Like this solution! When getting the data from the server, e.g. using `$http.get(...)` make sure to set `responseType:'arraybuffer'` like explained here: http://stackoverflow.com/questions/21628378/angularjs-display-blob-pdf-in-an-angular-app – Tim Büthe Sep 01 '15 at 15:33
  • Works in Chrome (Win), but Safari (Mac) just opens the blobbed file in the browser. (blob:https/...) Like that this solution lets me wait for my promises to be resolved though. – sekky Jun 22 '16 at 06:51
26

Try this

<a target="_self" href="mysite.com/uploads/ahlem.pdf" download="foo.pdf">

and visit this site it could be helpful for you :)

http://docs.angularjs.org/guide/

AhlemMustapha
  • 397
  • 3
  • 9
  • 7
    Beware of the ``download`` attribute that's still not supported by any IE nor Safari version. Check it out here : http://caniuse.com/#feat=download – Pierre-Adrien Nov 14 '14 at 11:18
  • When i use it with angular it take url to $urlRouterProvider and redirect to my default page, is there any solution to download a file instead of navigation – HardikDG Feb 25 '16 at 03:46
  • I always find it patronising when someone posts a link like that. – slugmandrew Apr 11 '19 at 10:44
23

This can be done in javascript without the need to open another browser window.

window.location.assign('url');

Replace 'url' with the link to your file. You can put this in a function and call it with ng-click if you need to trigger the download from a button.

mm8154
  • 479
  • 4
  • 7
14

In our current project at work we had a invisible iFrame and I had to feed the url for the file to the iFrame to get a download dialog box. On the button click, the controller generates the dynamic url and triggers a $scope event where a custom directive I wrote, is listing. The directive will append a iFrame to the body if it does not exist already and sets the url attribute on it.

EDIT: Adding a directive

appModule.directive('fileDownload', function ($compile) {
    var fd = {
        restrict: 'A',
        link: function (scope, iElement, iAttrs) {

            scope.$on("downloadFile", function (e, url) {
                var iFrame = iElement.find("iframe");
                if (!(iFrame && iFrame.length > 0)) {
                    iFrame = $("<iframe style='position:fixed;display:none;top:-1px;left:-1px;'/>");
                    iElement.append(iFrame);
                }

                iFrame.attr("src", url);


            });
        }
    };

    return fd;
});

This directive responds to a controller event called downloadFile

so in your controller you do

$scope.$broadcast("downloadFile", url);
Ketan
  • 5,782
  • 3
  • 28
  • 38
  • 1
    Code snippet would be a great help. – Sudhir N Oct 08 '13 at 09:21
  • The directive above is not working for me, when I put iframe creation outside scope.$on it creates iframe but $on event is not calling when using broadcast – Kanagu Dec 17 '13 at 07:31
  • Yes $scope.$broadcast works only on children. You can put the directive on the top level scope if possible. – Ketan Dec 17 '13 at 22:37
12

You can set location.href to a data URI containing the data you want to let the user download. Besides this, I don't think there's any way to do it with just JavaScript.

Jani Hartikainen
  • 40,227
  • 10
  • 60
  • 82
  • This works great for me, and was much cleaner than all the other things we were trying, or IMHO, the complicated approaches recommended above. Angular ignores it entirely. Or, you can also use window.open()/$window.open() if you want to try to open in another window. But you'll run into popup blockers in modern browsers... – XML Jan 06 '14 at 02:29
  • 1
    In Angular 1.3, `$location.href` changed to `$window.location.href` – igortg May 12 '15 at 18:39
  • This is a great answer. The following link on SO provides a full working example: https://stackoverflow.com/a/30889331/1625820 – herrtim Jun 27 '18 at 13:29
7

Would just like to add that in case it doesn't download the file because of unsafe:blob:null... when you hover over the download button, you have to sanitize it. For instance,

var app = angular.module('app', []);

app.config(function($compileProvider){

$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
Community
  • 1
  • 1
Samir Alajmovic
  • 2,862
  • 2
  • 23
  • 26
5

If you have access to on the server, consider setting headers as answered in this more general question.

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"

Reading the comments on that answer, it is advisable to use a more specific Content-Type than octet-stream.

Community
  • 1
  • 1
plong0
  • 2,098
  • 1
  • 17
  • 18
4

I had teh same problem and spend many hours find diferent solutions, and now I join all the comments in this post.I hope it, will be helpfull, my answer was correctly tested on Internet Explorer 11, Chrome and FireFox.

HTML :

<a href="#" class="btn btn-default" file-name="'fileName.extension'"  ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>

DIRECTIVE :

directive('fileDownload',function(){
    return{
        restrict:'A',
        scope:{
            fileDownload:'=',
            fileName:'=',
        },

        link:function(scope,elem,atrs){


            scope.$watch('fileDownload',function(newValue, oldValue){

                if(newValue!=undefined && newValue!=null){
                    console.debug('Downloading a new file'); 
                    var isFirefox = typeof InstallTrigger !== 'undefined';
                    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;
                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                    var isBlink = (isChrome || isOpera) && !!window.CSS;

                    if(isFirefox || isIE || isChrome){
                        if(isChrome){
                            console.log('Manage Google Chrome download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var downloadLink = angular.element('<a></a>');//create a new  <a> tag element
                            downloadLink.attr('href',fileURL);
                            downloadLink.attr('download',scope.fileName);
                            downloadLink.attr('target','_self');
                            downloadLink[0].click();//call click function
                            url.revokeObjectURL(fileURL);//revoke the object from URL
                        }
                        if(isIE){
                            console.log('Manage IE download>10');
                            window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName); 
                        }
                        if(isFirefox){
                            console.log('Manage Mozilla Firefox download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var a=elem[0];//recover the <a> tag from directive
                            a.href=fileURL;
                            a.download=scope.fileName;
                            a.target='_self';
                            a.click();//we call click function
                        }


                    }else{
                        alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
                    }
                }
            });

        }
    }
})

IN CONTROLLER:

$scope.myBlobObject=undefined;
$scope.getFile=function(){
        console.log('download started, you can show a wating animation');
        serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
        .then(function(data){//is important that the data was returned as Aray Buffer
                console.log('Stream download complete, stop animation!');
                $scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        },function(fail){
                console.log('Download Error, stop animation and show error message');
                                    $scope.myBlobObject=[];
                                });
                            }; 

IN SERVICE:

function getStream(params){
                 console.log("RUNNING");
                 var deferred = $q.defer();

                 $http({
                     url:'../downloadURL/',
                     method:"PUT",//you can use also GET or POST
                     data:params,
                     headers:{'Content-type': 'application/json'},
                     responseType : 'arraybuffer',//THIS IS IMPORTANT
                    })
                    .success(function (data) {
                        console.debug("SUCCESS");
                        deferred.resolve(data);
                    }).error(function (data) {
                         console.error("ERROR");
                         deferred.reject(data);
                    });

                 return deferred.promise;
                };

BACKEND(on SPRING):

@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
        @RequestBody Map<String,String> spParams
        ) throws IOException {
        OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}
havelino
  • 390
  • 4
  • 8
3

This worked for me in angular:

var a = document.createElement("a");
a.href = 'fileURL';
a.download = 'fileName';
a.click();
Zohab Ali
  • 4,958
  • 3
  • 31
  • 43
  • If you have a string you want to download, just change fileURL to `data:text/plain;base64,${btoa(theStringGoesHere)}` – Chicken Suop Apr 04 '19 at 08:49
2

I didnt want Static Url. I have AjaxFactory for doing all ajax operations. I am getting url from the factory and binding it as follows.

<a target="_self" href="{{ file.downloadUrl + '/' + order.OrderId + '/' + fileName }}" download="{{fileName}}">{{fileName}}</a>

Thanks @AhlemMustapha

om471987
  • 4,741
  • 4
  • 27
  • 39