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.c
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");
}
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();
});
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 -
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!
You can just navigate:
location.href = "http://"+$localStorage.ip+":"+$localStorage.port+"/exportDB";
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();