Guy Ben-Moshe
Guy Ben-Moshe

Reputation: 934

AngularJS - Receive and download CSV

I am using a nodeJS program as a server and an AngularJS web application as the client.

To create the CSV I'm using the "express-csv" library (https://www.npmjs.com/package/express-csv)

Here is my server side code:

Defines:

var app = express();
var csv = require('express-csv');

Get code:

app.get('/exportDB', function(req, res){
    res.csv([
    ["a", "b", "c"]
  , ["d", "e", "f"]
  ]);

Here is my client side code:

$http.get("http://"+$localStorage.ip+":"+$localStorage.port+"/exportDB").success(function(response){
            // HERE I NEED A WAY TO DOWNLOAD THE RECEIVED CSV
        });

Needless to say it reaches the server and everything else is working just fine, but I couldnt find a way to download the CSV. Help please.

P.S

Please don't say it's a duplicate of Prompt a csv file to download as pop up using node.js and node-csv-parser (node module) since the client side isn't really mentioned there. Also, other questions are focused on server side instead of client. There is no other question referring to AngularJS client.

Upvotes: 9

Views: 10582

Answers (5)

Kabiraj Kharel
Kabiraj Kharel

Reputation: 205

Here I tried to make it simple. Assign all the back end records that you want to display in the file in the variable called obj. I will just say it as var obj = []. And inside the function just add the below code.

var a = document.createElement("a");
var csvContent = "Name, Address\n";

for(var i =0; i <obj.lenght; i++ ) {
  var dataString = obj[i].name + ", " + obj[i].address + "\n";
  csvContent +=  dataString;  
}
a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(csvContent);
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click(); 

Upvotes: 1

Shalaka Deshpande
Shalaka Deshpande

Reputation: 166

I faced same issue that the solutions mentioned above with works well with Chrome and Firefox, but not with safari/IE.

Tried out following hack and it worked for me-

var url="http://'+$localStorage.ip+':"+$localStorage.port+'/exportDB'; var form = angular.element("<form action='" + url +"'></form>"); form.submit();

File download will be handled by browser itself. though following is limitation to it -

  1. You won't be able to handle the errors (if any) from your http get call :( For this tried using try-catch block of javascript, but didn't work well...
  2. ..you wont be able to unit test this piece of code :( :(

There is another approach that worked and it was -

var url="http://'+$localStorage.ip+':"+$localStorage.port+'/exportDB'; $window.location.href = url;

Suggestions and Discussions welcome!

Upvotes: 2

Rakesh Chand
Rakesh Chand

Reputation: 3113

There are ways of downloading csv. First approach is to create a tag and click it

Add the mimeType in below code data:application/octet-stream

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(); 

But this solution doesn't work on IE>9 and safari>6

because safari doesn't follow download attribute for anchor tag

so for safari you can use filesaver.js

and IE this solution will work

if (window.navigator.msSaveOrOpenBlob){
                // base64 string
                var base64str = response;

                // decode base64 string, remove space for IE compatibility
                var newstr =base64str.replace(/\s/g, '');
                var binary = atob(newstr);

                // get binary length
                var len = binary.length;

                // create ArrayBuffer with binary length
                var buffer = new ArrayBuffer(len);

                // create 8-bit Array
                var view = new Uint8Array(buffer);

                // save unicode of binary data into 8-bit Array
                for (var i = 0; i < len; i++) {
                 view[i] = binary.charCodeAt(i);
                }

                // create the blob object with content-type "application/csv"               
                var blob = new Blob( [view], { type: mimeType });
                window.navigator.msSaveOrOpenBlob(blob, "Name your file here");
            }

Upvotes: 1

jcubic
jcubic

Reputation: 66488

You can create a tag and click on it:

    $http.get("http://"+$localStorage.ip+":"+$localStorage.port+"/exportDB").success(function(response) {
        var dataURI = 'data:application/octet-stream;base64,' + btoa(response);
        $('<a></a>').attr({
            download:  'db.csv',
            href: dataURI
        })[0].click();
    });

Upvotes: 1

karaxuna
karaxuna

Reputation: 26930

You can just navigate:

location.href = "http://"+$localStorage.ip+":"+$localStorage.port+"/exportDB";

Upvotes: 2

Related Questions