2

Node service: shown below are node service call where getting data from mysql query. And converting to json2csv format.

function getData(req,res){
        var json2csv = require('json2csv');
        var resultset = {};
        resultset.data = [];
        var nodeExcel=require('excel-export');
        var dateFormat = require('dateformat');
        var queryString = "select name ,class ,fname from details"

     connection.query(queryString, function(err, result) {
         if(err) {
                        console.log('error ',err);
                        resultset.success=false;
                            res.writeHead(200, {
                                'Content-Type': 'application/json'
                              });
                            var resultData =resultset;
                            res.write(JSON.stringify(resultData));
                              res.end();
                    } else {
                        if(result.length>0) {
                            for(var i=0;i<result.length;i++) {
                                resultset.data[i]={};
                                var arr=_(result[i]).toArray();

                                resultset.data[i].name=arr[0]!=null?arr[0]:null;
                                resultset.data[i].class=arr[1]!=null?arr[1]:null;
                                resultset.data[i].fname=arr[2]!=null?arr[2]:null;
                            }
                            resultset.success=true;
                            res.writeHead(200, {
                                'Content-Type': 'application/json'
                              });
                            var resultData =json2csv(resultset);
                            console.log("resultData",resultData);
                            res.write(JSON.stringify(resultData));
                              res.end();
                        }   
                        else{
                            resultset.success = false;
                            res.writeHead(200, {
                                'Content-Type': 'application/json'
                            });
                            var resultData = resultset;
                            res.write(JSON.stringify(resultData));
                            res.end();
                        }
                    }
            });


    }

Controller:

getting the service response.

$scope.Details=function(data,fileName){
    $http.get(Data.baseNodeService+'getData',headconfig).then(function(response,fileName){ 
    $scope.det = response.data.data;
    var element = angular.element('');
      var anchor = angular.element('<a/>');
     anchor.attr({
         href: 'data:attachment/csv;charset=utf-8,' + encodeURI($scope.det),
         target: '_blank',
         download: 'filename.csv'
     })[0].click();
    });
}

On click Html Download:

<input type="button" class="bt-submit" ng-click="Details()" value="Download" />

But I am getting download output as [object Object].I want to get data from my service call and download in csv format.

2 Answers 2

1

You can download CSV in different ways, this below is a common way to download file

var a = document.createElement('a');
 a.href = 'data:'+mimeType+';charset=utf-8;base64,' + response;
 a.target = '_blank';
 a.download = "name the file here";
 document.body.appendChild(a);
 a.click(); 

use the mimeType as your file type here for csv it would be attachment/csv but this won;t work on safari.

There is awseome library https://github.com/alferov/angular-file-saver You can use this.

You can call it like

function download(api, file, contentType) {
    var d = $q.defer();
    $http({
        method: 'GET',
        url: api,
        responseType: 'arraybuffer',
        headers: {
            'Content-type': contentType
        }
    }).success(function(response) {
        var data = new Blob([response], {
            type: contentType+ ';charset=utf-8'
        });
        FileSaver.saveAs(data, file);
        d.resolve(response);
    }).error(function(response) {
        d.reject(response);
    });
    return d.promise;
}

Also see my other answers on file download

how to export data into CSV and PDF files using angularjs

And

AngularJS - Receive and download CSV

Sign up to request clarification or add additional context in comments.

5 Comments

what type of content you get from service response
I m getting response like ""\"name\",\"class\",\"fname\"…",\"abc\",\"nodeclass\"""
does that make sense ? what are you getting for csv means => base64 string or what ?
Use stackoverflow as a tool to get hints and logics not exact answers, just do a little research, you’ll get one of the above ways to work for you
Glad to help mate, that’s how you learn it, I would have given you right answer but what would you learn from that., right!
1

Try this:-

/*this section for CSV*/
    if(window.navigator.msSaveOrOpenBlob && window.Blob) {
        var blob = new Blob([response.data.data], {type: "text/csv"});
        navigator.msSaveOrOpenBlob(blob, new Date().getTime() + '.csv');
    } else {
        var anchor = angular.element('<a/>').css({display: 'none'});
        angular.element(document.body).append(anchor); // Attach to document
        anchor.attr({
            href: 'data:attachment/csv;charset=utf-8,' + encodeURI(response.data.data),
            target: '_blank',
            download: new Date().getTime() + '.csv'
        })[0].click();
        anchor.remove();
    }

4 Comments

csvContent is undefine?
csvContent is your csv data variable and you have to write it in your controller
use your response.data.data at csvContent variable
file is downloading and giving output as [object Object] [object Object] [object Object] [object Object] [object Object] [object Object]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.