Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download Client Side Json as CSV

I am using the angularJS frontend framework and nodejs/express as a backend server to send and receive JSON. The backend sent a large JSON object to the frontend and I was wondering if I could download the JSON object from the frontend in CSV format.

The data is stored as json in an scope variable: $scope.data in an angular controller. Then I converted the data to a string in CSV format in the variable $scope.CSVdata. How do I get the CSVdata to download from the client browser?

I know nodejs can be set up to send a file in CSV format but it would be nice to keep the backend a clean JSON api.

like image 828
GTDev Avatar asked Mar 28 '13 18:03

GTDev


1 Answers

Referencing this post I've thrown together quick demonstration on how this may be done using AngularJS:

JavaScript Demo (Plunker)

I've wrapped the referenced Base64 code in a service, and use it in the following way:

$scope.downloadCSV = function() {
  var data = Base64.encode($scope.CSVData);
  window.location.href = "data:text/csv;base64," + data;
};

There are some disadvantages to this method however as mentioned in the comments. I've pulled out some bullet points from the Wikipedia page on this subject. Head over there for the full list.

  • Data URIs are not separately cached from their containing documents (e.g. CSS or HTML files), therefore the encoded data is downloaded every time the containing documents are re-downloaded.
  • Internet Explorer 8 limits data URIs to a maximum length of 32 KB. (Internet Explorer 9 does not have this limitation)
  • In IE 8 and 9, data URIs can only be used for images, but not for navigation or JavaScript generated file downloads.[7]
  • Base64-encoded data URIs are 1/3 times larger in size than their binary equivalent. (However, this overhead is reduced to 2–3% if the HTTP server compresses the response using gzip)
  • Data URIs do not carry a filename as a normal linked file would. When saving, a default filename for the specified MIME type is generally used.
  • [ . . . ]
like image 198
Jay Avatar answered Oct 19 '22 23:10

Jay