1

I have made a Java micro service to export a table from a database into a CSV file and get it in browser by following this: Downloading a CSV File in Browser by using Java It works well and I get the file in the browser when I call the URL (by copying and pasting in the browser) : http://localhost:8080/api/fileDownload/2

In the Angular part when I call the URL in my app I see in the console :

Request URL:http://localhost:8080/api/fileDownload/2
Request Method:GET
Status Code:200 

In the preview and the response of the console, I also have the content of my file. So it seems everything looks good but the problem is that my browser doesn't download the file automatically.

My controller :

vm.downloadFunction=function(){
    FileDownload.download.query({id:2},function(data){
    });
};

My view :

 <label data-ng-click="addModule.downloadFunction()" class="btn btn-link btn-file">
                    Download <input type="button" class="hidden">
                </label>

And the service :

voltApp.factory('FileDownload', function ($resource) {
return{
    download:  $resource('/api/fileDownload/:id', {}, {
        query: {method: 'GET', params: {id:'@id'},isArray:false},
        update:{method: 'PUT'}
    })
};

});

What am I doing wrong?

Community
  • 1
  • 1
John
  • 185
  • 1
  • 6
  • 21
  • This post was very helpul too! http://stackoverflow.com/questions/14215049/how-to-download-file-using-angularjs-and-calling-mvc-api – John Jan 20 '17 at 09:14

1 Answers1

0

Consider using ngFileSaver

Example:

JS

function ExampleCtrl(FileSaver, Blob) {
  var vm = this;

  vm.val = {
    text: 'Hey ho lets go!'
  };

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

angular

      .module('fileSaverExample', ['ngFileSaver'])
      .controller('ExampleCtrl', ['FileSaver', 'Blob', ExampleCtrl]);

HTML

<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>
Matheno
  • 4,112
  • 6
  • 36
  • 53